#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CC 的工作收件箱。

把你在客厅里【私聊 CC】和【群里 @CC】说的话，一次性收集出来——
这样你平时在 App 里随手跟 CC 提的想法/意见，等你来"开发窗口"找我时，
我（真实的 CC）跑一下这个脚本就能一口气看完，然后动手改客厅。

用法：  python3 cc_inbox.py
"""
import os
import sqlite3
import time

DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lounge.db")


def fmt(ts):
    return time.strftime("%m-%d %H:%M", time.localtime(ts / 1000))


def main():
    if not os.path.exists(DB):
        print("还没有 lounge.db（先把 server.py 跑起来）。")
        return
    conn = sqlite3.connect(DB)
    conn.row_factory = sqlite3.Row

    # CC 的一对一会话 id
    dm = conn.execute("SELECT id FROM conversations WHERE type='dm' AND title='CC'").fetchone()
    dm_id = dm["id"] if dm else -1

    rows = conn.execute(
        """
        SELECT m.text, m.ts, c.type AS ctype, c.title AS ctitle
        FROM messages m JOIN conversations c ON c.id = m.conv_id
        WHERE m.speaker='user' AND ( m.conv_id=? OR m.text LIKE '%@CC%' )
        ORDER BY m.id ASC
        """,
        (dm_id,),
    ).fetchall()
    conn.close()

    items = [r for r in rows]
    n = len(items)
    print("=" * 48)
    print(f" CC 收件箱 · 共 {n} 条给 CC 的话" + ("（够 5 条了，该处理了）" if n >= 5 else ""))
    print("=" * 48)
    if not items:
        print(" （暂时没有。在 App 里私聊 CC 或群里 @CC 就会收进来。）")
        return
    for r in items:
        where = "私聊" if r["ctype"] == "dm" else f"群「{r['ctitle']}」@CC"
        print(f"\n[{fmt(r['ts'])} · {where}]\n  {r['text']}")
    print()


if __name__ == "__main__":
    main()
