"""Reset coba 系統到「乾淨可給團隊試用」狀態。

【清掉(回到 0)】
  - tasks(全部含 done / cancelled / 軟刪都 hard delete)
  - messages(NAS 鏡像的歷史訊息)
  - agent_activities(Cooper 動態 / 簡報 / 派工偵測 / ack / classify / reflection_note 全部)
  - meetings + transcripts + summaries + decisions + action_items
  - projects
  - line_binding_codes(過期的綁定碼,active 綁定保留)
  - Qdrant 「messages」collection(reflection 相似度 index 重置)

【保留(基礎設施,別動)】
  - users(team 4 人)
  - channels(LINE 群組 / 各人 1對1 私訊 mapping)
  - line bindings(user.line_user_id 不動 — 同仁不用重綁)

跑前確認:
  - uvicorn 暫停 5 秒(避免併寫)→ 跑 → 啟回
  - 印 before / after counts
"""
import os, sys
ENV = "/volume1/homes/robertsu/coba/app/.env"
if os.path.exists(ENV):
    for l in open(ENV):
        if "=" in l and not l.startswith("#"):
            k, v = l.strip().split("=", 1); os.environ.setdefault(k, v)
sys.path.insert(0, "/volume1/homes/robertsu/coba/app")

import asyncio
import shutil
from pathlib import Path
from sqlalchemy import select, func, delete
from app.database import AsyncSessionLocal
from app.models.task import Task, Project
from app.models.channel import Message, Channel
from app.models.agent_activity import AgentActivity
from app.models.user import User
from app.models.meeting import Meeting, MeetingTranscript, MeetingSummary, MeetingDecision, MeetingActionItem
from app.models.line_binding import LineBindingCode


async def count_table(db, model):
    return (await db.execute(select(func.count()).select_from(model))).scalar() or 0


async def main():
    print("="*60)
    print(" reset_to_clean.py — 清業務資料,保留基礎設施")
    print("="*60)

    async with AsyncSessionLocal() as db:
        # === Before ===
        print("\n=== BEFORE ===")
        before = {
            "users": await count_table(db, User),
            "channels": await count_table(db, Channel),
            "tasks": await count_table(db, Task),
            "messages": await count_table(db, Message),
            "agent_activities": await count_table(db, AgentActivity),
            "meetings": await count_table(db, Meeting),
            "projects": await count_table(db, Project),
            "line_binding_codes": await count_table(db, LineBindingCode),
        }
        for k, v in before.items():
            print(f"  {k:24s} = {v}")
        # 印保留的 user
        print("\n  保留的 users(LINE 綁定狀態):")
        users = (await db.execute(select(User).where(User.deleted_at.is_(None)))).scalars().all()
        for u in users:
            line_bound = bool(u.line_user_id)
            print(f"    - {u.display_name:20s} email={u.email}  LINE={'✓' if line_bound else '✗'}")
        print("\n  保留的 channels:")
        chs = (await db.execute(select(Channel).where(Channel.deleted_at.is_(None)))).scalars().all()
        for c in chs:
            print(f"    - {c.name:30s} ({c.line_source_type or 'web'})")

        # === Wipe ===
        print("\n=== 開始清除 ===")

        # 注意刪除順序:有 FK 的先刪 child
        await db.execute(delete(MeetingActionItem));      print("  ✓ meeting_action_items")
        await db.execute(delete(MeetingDecision));         print("  ✓ meeting_decisions")
        await db.execute(delete(MeetingSummary));          print("  ✓ meeting_summaries")
        await db.execute(delete(MeetingTranscript));       print("  ✓ meeting_transcripts")
        await db.execute(delete(Meeting));                 print("  ✓ meetings")
        await db.execute(delete(AgentActivity));           print("  ✓ agent_activities")
        await db.execute(delete(Task));                    print("  ✓ tasks (含已軟刪)")
        await db.execute(delete(Message));                 print("  ✓ messages")
        await db.execute(delete(Project));                 print("  ✓ projects")
        await db.execute(delete(LineBindingCode));         print("  ✓ line_binding_codes")
        await db.commit()

        # === After ===
        print("\n=== AFTER ===")
        after = {
            "users": await count_table(db, User),
            "channels": await count_table(db, Channel),
            "tasks": await count_table(db, Task),
            "messages": await count_table(db, Message),
            "agent_activities": await count_table(db, AgentActivity),
            "meetings": await count_table(db, Meeting),
            "projects": await count_table(db, Project),
            "line_binding_codes": await count_table(db, LineBindingCode),
        }
        for k, v in after.items():
            keep = "(保留)" if k in ("users", "channels") else ""
            print(f"  {k:24s} = {v}  {keep}")

    # === Qdrant collection 清空 ===
    print("\n=== 清 Qdrant messages collection ===")
    try:
        from qdrant_client import AsyncQdrantClient
        QDRANT_DIR = "/volume1/homes/robertsu/coba/app/qdrant_data"
        # uvicorn 還在跑 — 走 lock 風險。安全做法:刪整個 qdrant_data 資料夾(uvicorn 重啟會重建)
        # 但 collections.json + segments 都被 process 持有。
        # 替代:用 client 連線 delete points (空 collection 比較難)→ 直接 delete collection 然後 uvicorn 重啟自動 create。
        c = AsyncQdrantClient(path=QDRANT_DIR)
        try:
            await c.delete_collection("messages")
            print("  ✓ Qdrant messages collection deleted")
        except Exception as e:
            print(f"  ⚠ Qdrant delete failed (uvicorn 持有 lock):{e}")
        finally:
            await c.close()
    except Exception as e:
        print(f"  ⚠ Qdrant client 載入失敗(可在 uvicorn 重啟後再清):{e}")

    # 額外:LINE 媒體下載資料夾(空檔案沒用)
    media = Path("/volume1/homes/robertsu/coba/uploads/line")
    if media.exists():
        files = list(media.glob("*"))
        for f in files:
            try:
                f.unlink()
            except Exception:
                pass
        print(f"  ✓ 清掉 LINE 媒體 {len(files)} 個檔")

    print("\n" + "="*60)
    print(" 完成。系統回到「team 試用前」乾淨狀態。")
    print(" 任務、訊息、Cooper 動態、體悟、會議、Qdrant 全清。")
    print(" Users + LINE 綁定 + Channels 都保留 — 同仁不用重做設定。")
    print("="*60)


asyncio.run(main())
