#!/usr/bin/env python3
"""
选题日报 — 每天早上分析 we-mp-rss 文章，生成选题推荐，推送到企微群
用法: cd ~/project/scripts && ~/project/we-mp-rss-main源文件/we-mp-rss-main/venv/bin/python3 daily_topics.py
"""
import json, os, re, sqlite3, shutil, time
from datetime import datetime, timezone, timedelta
from collections import Counter

import requests

# ── 配置 ───────────────────────────────────────────────
CST = timezone(timedelta(hours=8))
DB_PATH = os.path.expanduser("~/project/we-mp-rss-data/db.db")
WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d4de64e1-efaa-4f03-a833-ad85c1d6de5b"

# DeepSeek API
_env = os.path.expanduser("~/project/.env")
for line in open(_env, encoding="utf-8"):
    line = line.strip()
    if line and not line.startswith("#") and "=" in line:
        k, _, v = line.partition("=")
        k, v = k.strip(), v.strip().strip('"').strip("'")
        if k: os.environ[k] = v

DEEPSEEK_KEY = os.getenv("DEEPSEEK_API_KEY", "")
DEEPSEEK_URL = "https://api.deepseek.com/chat/completions"

# ── 数据获取 ─────────────────────────────────────────────
def get_db():
    """复制数据库避免锁"""
    copy = "/tmp/daily_topics.db"
    shutil.copy2(DB_PATH, copy)
    db = sqlite3.connect(copy)
    db.row_factory = sqlite3.Row
    return db

def get_recent_articles(hours=36):
    """获取最近 N 小时的文章"""
    db = get_db()
    cutoff = int((datetime.now(CST) - timedelta(hours=hours)).timestamp())
    rows = db.execute("""
        SELECT a.id, a.title, a.url, a.description, a.publish_time,
               f.mp_name as source
        FROM articles a JOIN feeds f ON a.mp_id = f.id
        WHERE a.publish_time >= ?
        ORDER BY a.publish_time DESC
    """, (cutoff,)).fetchall()
    db.close()
    return [dict(r) for r in rows]

# ── AI 分析 ─────────────────────────────────────────────
def analyze_topics(articles):
    """调用 DeepSeek 分析今日选题"""
    if not articles:
        return "📭 近 36 小时无新文章，可能是抓取暂停。检查登录状态。"

    summaries = []
    for a in articles:
        t = datetime.fromtimestamp(a["publish_time"], CST).strftime("%m-%d %H:%M")
        summaries.append(f"- [{a['source']}] {a['title']} ({t})")

    prompt = f"""你是广东春季高考（3+证书考试）领域的资深内容编辑。分析以下今日抓取的文章，给出选题建议。

今日文章（{len(articles)}篇）：
{chr(10).join(summaries)}

请按以下格式输出（纯文本，不用 markdown 表格，**中文字数必须严格控制在 1200 字以内，每个选题只用 2 句概括**，因为推送渠道有字节限制！）：

📊 今日概况
[2-3句话总结今日文章的主要话题和趋势]

🔥 值得追的选题（3-5个）
对每个选题：
选题：xxx
为什么：1-2句话说明为什么值得做
切入角度：2-3个不同的切入方向
参考文章：[来源] 标题

💡 可储备选题（2-3个）
值得关注但不必今天做的话题

⚠️ 注意事项
今天发布需要注意的时间节点或政策动态提醒"""

    resp = requests.post(DEEPSEEK_URL, json={
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7,
        "max_tokens": 3000,
    }, headers={"Authorization": f"Bearer {DEEPSEEK_KEY}"}, timeout=60)

    if resp.status_code == 200:
        return resp.json()["choices"][0]["message"]["content"]
    return f"❌ AI 分析失败: HTTP {resp.status_code}"

# ── 推送 ────────────────────────────────────────────────
def push(content):
    """推送到企微群。注意：企微 markdown 限制是 4096 BYTES（不是字符）！"""
    max_bytes = 4000
    encoded = content.encode("utf-8")
    if len(encoded) > max_bytes:
        truncated = ""
        for ch in content:
            if len((truncated + ch).encode("utf-8")) > max_bytes - 60:
                break
            truncated += ch
        content = truncated + "\n\n...(截断)"

    data = {"msgtype": "markdown", "markdown": {"content": content}}
    r = requests.post(WEBHOOK, json=data, timeout=10)
    if r.status_code == 200 and r.json().get("errcode") == 0:
        print(f"[{datetime.now(CST).strftime('%H:%M')}] 选题日报已推送 ({len(content)}字/{len(content.encode('utf-8'))}bytes)")
    else:
        print(f"推送失败: {r.text[:200]}")

# ── 主流程 ──────────────────────────────────────────────
if __name__ == "__main__":
    articles = get_recent_articles(36)
    print(f"获取到 {len(articles)} 篇文章")
    report = analyze_topics(articles)
    push(report)
