"""清掉昨晚錯建的「記錄覆盤」任務 + 把漏歸檔的覆盤手動寫進 reflection_note。"""
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
from datetime import datetime, timezone
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.task import Task
from app.models.user import User
from app.models.agent_activity import AgentActivity


async def main():
    async with AsyncSessionLocal() as db:
        # 1. 軟刪「記錄覆盤」開頭且 status=todo 的任務
        wrong = (await db.execute(
            select(Task).where(
                Task.deleted_at.is_(None),
                Task.title.like("記錄覆盤:%"),
            )
        )).scalars().all()
        print(f"找到 {len(wrong)} 筆錯誤「記錄覆盤」任務:")
        now = datetime.now(timezone.utc)
        for t in wrong:
            print(f"  - 刪 「{t.title}」 status={t.status}")
            t.deleted_at = now
            t.status = "cancelled"
        await db.commit()

        # 2. 找 Robert
        robert = (await db.execute(
            select(User).where(User.email == "ssbb30529@gmail.com")
        )).scalar_one_or_none()

        # 3. 補寫漏歸檔的「拍攝間鐵皮」覆盤
        if robert:
            content = "盛豪拍攝間用新的鐵皮去蓋 會比 用中古冷凍庫板去蓋 還要有質感"
            summary = "拍攝間建材新鐵皮優於中古冷凍庫板"
            existing = (await db.execute(
                select(AgentActivity).where(
                    AgentActivity.activity_type == "reflection_note",
                    AgentActivity.user_id == robert.id,
                )
            )).scalars().all()
            already = any((a.extra or {}).get("summary") and "鐵皮" in (a.extra or {}).get("summary") for a in existing)
            if already:
                print("  「拍攝間鐵皮」覆盤已歸檔,跳過")
            else:
                db.add(AgentActivity(
                    activity_type="reflection_note",
                    user_id=robert.id,
                    summary=f"體悟:{summary}",
                    extra={
                        "raw": content,
                        "summary": summary,
                        "tag": "流程",
                        "similar_to": [],
                        "similar_count": 0,
                        "via": "manual_backfill",
                    },
                ))
                await db.commit()
                print(f"  ✓ 補寫「{summary}」到 reflection_note")

asyncio.run(main())
