#!/home/ubuntu/project/we-mp-rss-main/venv/bin/python3
"""
gdcjgk-每日发布 数据采集脚本
查询 we-mp-rss 数据库最近 36 小时文章，输出格式化文本供 AI 分析。
用法: python3 daily_gdcjgk_data.py [hours=36]
"""
import sqlite3, json, sys
from datetime import datetime, timezone, timedelta

HOURS = int(sys.argv[1]) if len(sys.argv) > 1 else 36
DB_PATH = "/home/ubuntu/project/we-mp-rss-data/db.db"
CALENDAR_PATH = "/home/ubuntu/project/config/exam_calendar.json"
IMAGE_LIB_PATH = "/home/ubuntu/.hermes/data/image_library.json"

beijing = timezone(timedelta(hours=8))
now = datetime.now(beijing)
cutoff_ts = int((now - timedelta(hours=HOURS)).timestamp())

# ── 1. 查询文章 ──
try:
    db = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)
    db.row_factory = sqlite3.Row
    rows = db.execute("""
        SELECT a.id, a.title, a.url, a.publish_time, a.description, f.mp_name
        FROM articles a JOIN feeds f ON a.mp_id = f.id
        WHERE a.publish_time > ?
        ORDER BY a.publish_time DESC
    """, (cutoff_ts,)).fetchall()
    total_count = db.execute("SELECT COUNT(*) FROM articles").fetchone()[0]
    latest = db.execute("SELECT MAX(publish_time) FROM articles").fetchone()[0]
    db.close()
except Exception as e:
    print(f"DB_ERROR: {e}")
    sys.exit(1)

# ── 2. 考试日历 ──
try:
    with open(CALENDAR_PATH) as f:
        calendar = json.load(f)
except Exception:
    calendar = {"events": []}

future_events = []
for ev in calendar.get("events", []):
    if not isinstance(ev, dict) or "date" not in ev:
        continue
    parts = ev["date"].split("-")
    if len(parts) != 2:
        continue
    event_date = datetime(now.year, int(parts[0]), int(parts[1]), tzinfo=beijing)
    if event_date < now:
        event_date = datetime(now.year + 1, int(parts[0]), int(parts[1]), tzinfo=beijing)
    days_left = (event_date - now).days
    if 0 <= days_left <= 30:
        future_events.append((days_left, ev["title"], ev.get("topics", [])))
future_events.sort()

# ── 3. 缩略图库统计 ──
try:
    with open(IMAGE_LIB_PATH) as f:
        images = json.load(f)
    img_count = len(images) if isinstance(images, list) else len(images.get("images", []))
except Exception:
    img_count = "未知"

# ── 4. 输出 ──
latest_str = datetime.fromtimestamp(latest, beijing).strftime("%Y-%m-%d %H:%M") if latest else "无"
print(f"# gdcjgk 每日发布数据 ({now.strftime('%Y-%m-%d %H:%M')} 采集)")
print(f"## 数据库概况")
print(f"- 总文章数: {total_count}")
print(f"- 最新文章时间: {latest_str}")
print(f"- 查询窗口: 最近 {HOURS} 小时")
print(f"- 窗口内文章数: {len(rows)}")
print(f"- 缩略图库: {img_count} 张")
print()

if rows:
    print("## 候选文章列表")
    print("| # | 时间 | 来源 | 标题 | 摘要 |")
    print("|---|------|------|------|------|")
    for i, r in enumerate(rows, 1):
        pt = datetime.fromtimestamp(r["publish_time"], beijing).strftime("%m-%d %H:%M")
        title = r["title"].replace("|", "｜")[:50]
        desc = (r["description"] or "").replace("|", "｜")[:30]
        print(f"| {i} | {pt} | {r['mp_name']} | {title} | {desc} |")
    print()
    print("## 文章详情")
    for i, r in enumerate(rows, 1):
        pt = datetime.fromtimestamp(r["publish_time"], beijing).strftime("%m-%d %H:%M")
        desc = (r["description"] or "").strip()[:150]
        print(f"### {i}. [{pt}] {r['mp_name']}：《{r['title']}》")
        print(f"   ID: {r['id']}")
        print(f"   摘要: {desc}")
        print(f"   链接: {r['url']}")
        print()
else:
    print("## ⚠ 查询窗口内无新文章")
    print(f"数据库最新文章为 {latest_str}，超出 {HOURS} 小时窗口。")
    print()

if future_events:
    print("## 未来 30 天考试日历")
    for days_left, title, topics in future_events:
        print(f"- ⏰ {days_left}天后: {title}")
else:
    print("## 未来 30 天考试日历: 无临近节点")
