import json, time, re
from pathlib import Path

OUT = Path("posts.jsonl")

def clean_line(s: str) -> str:
    s = (s or "").strip()
    s = re.sub(r'^\d+\s*[\.\)、-]\s*', '', s)   # 去编号
    s = s.strip().strip('"').strip("'")        # 去引号
    s = re.sub(r'\s+', ' ', s)
    return s

def ensure_format(line: str) -> str:
    # 统一为：TEXT=... || CTA=... || TAGS=...
    if "TEXT=" in line and "CTA=" in line and "TAGS=" in line:
        return line

    parts = [p.strip() for p in line.split("|")]
    text = parts[0] if parts and parts[0] else line
    cta = parts[1] if len(parts) >= 2 and parts[1] else "你会想试试哪一款？"
    tags = parts[2] if len(parts) >= 3 and parts[2] else "#曼彻斯特美食 #探店"

    cta = re.sub(r'^(CTA:|cta:)\s*', '', cta).strip()
    tags = re.sub(r'^(TAGS:|tags:)\s*', '', tags).strip()
    if "#" not in tags:
        tags = "#曼彻斯特美食 #探店"

    return f"TEXT={text} || CTA={cta} || TAGS={tags}"

def ollama_generate(model="llama3.2", temperature=0.7, num=5, timeout=20, retries=2):
    # 只依赖 requests，避免流式卡住
    import requests

    prompt = f"""
你是餐饮门店的社交媒体运营，只输出内容本身。
输出{num}条中文短帖，每条独立一行。
规则：
- 60~140字，像真人分享
- 每条有场景（下班/周末/雨天/约会/外卖/加班/通勤）
- 每条最后加上： | CTA:xxx | TAGS:#xxx #xxx
- 不要编号，不要引号，不要解释
城市：Manchester
"""

    url = "http://127.0.0.1:11434/api/generate"
    payload = {
        "model": model,
        "prompt": prompt,
        "stream": False,
        "options": {"temperature": temperature},
    }

    last_err = None
    for _ in range(retries + 1):
        try:
            r = requests.post(url, json=payload, timeout=timeout)
            r.raise_for_status()
            data = r.json()
            return data.get("response", "")
        except Exception as e:
            last_err = e
            time.sleep(1.0)
    raise RuntimeError(f"Ollama generate failed: {last_err}")

def save_posts(platform: str, posts):
    ts = int(time.time())
    OUT.parent.mkdir(parents=True, exist_ok=True)
    with OUT.open("a", encoding="utf-8") as f:
        for p in posts:
            f.write(json.dumps({"ts": ts, "platform": platform, "status": "draft", "text": p}, ensure_ascii=False) + "\n")

def main():
    try:
        raw = ollama_generate()
    except Exception as e:
        # 兜底：永远不空
        raw = "下班路上想吃点热乎的？来店里坐坐吧 | CTA:你最想点哪个？ | TAGS:#曼彻斯特美食 #探店"

    lines = [clean_line(x) for x in raw.splitlines() if clean_line(x)]
    # 再兜底：如果模型返回成一大段，就按句号切成几条
    if len(lines) <= 1 and raw:
        chunks = re.split(r'[。！？]\s*', raw)
        lines = [clean_line(c) for c in chunks if clean_line(c)]

    # 过滤掉太短的
    lines = [ln for ln in lines if len(ln) >= 12]

    # 永远至少一条
    if not lines:
        lines = ["下班路上想吃点热乎的？来店里坐坐吧 | CTA:你最想点哪个？ | TAGS:#曼彻斯特美食 #探店"]

    posts = [ensure_format(ln) for ln in lines[:5]]
    save_posts("X", posts)

    print("已生成：")
    for i, p in enumerate(posts, 1):
        print(i, p)

if __name__ == "__main__":
    main()
