"""Debug task_acceptance:直接呼叫 try_link_acceptance 看哪步把它擋下。"""
import asyncio
import os
import sys

ENV = "/volume1/homes/robertsu/coba/app/.env"
if os.path.exists(ENV):
    for line in open(ENV):
        if "=" in line and not line.startswith("#"):
            k, v = line.strip().split("=", 1)
            os.environ.setdefault(k, v)

sys.path.insert(0, "/volume1/homes/robertsu/coba/app")

from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.agent_activity import AgentActivity
from app.models.channel import Message
from app.models.task import Task
from app.models.user import User
from app.services.task_acceptance import _has_accept_hint, try_link_acceptance, ACCEPT_WINDOW_HOURS


async def main():
    async with AsyncSessionLocal() as db:
        aliu = (await db.execute(
            select(User).where(User.display_name.contains("阿綠")).limit(1)
        )).scalar_one_or_none()
        # 找阿綠最近的「OK 收到」訊息
        recent_aliu = (await db.execute(
            select(Message)
            .where(Message.user_id == aliu.id, Message.deleted_at.is_(None))
            .order_by(Message.created_at.desc())
            .limit(10)
        )).scalars().all()
    print(f"阿綠最近 10 則訊息:")
    for m in recent_aliu:
        hint = _has_accept_hint(m.content or "")
        print(f"  {m.created_at} hint={hint!s:5} {m.content[:60]!r}")

    # 找最後一則「OK 收到」
    target = next((m for m in recent_aliu if "OK 收到" in (m.content or "")), None)
    if target is None:
        print("找不到「OK 收到」訊息")
        return
    print(f"\n要 debug 的訊息:{target.id} {target.content!r} channel={target.channel_id}")

    # 看最近 24hr task_create_auto for 阿綠
    cutoff = datetime.now(timezone.utc) - timedelta(hours=ACCEPT_WINDOW_HOURS)
    async with AsyncSessionLocal() as db:
        acts = (await db.execute(
            select(AgentActivity).where(
                AgentActivity.activity_type == "task_create_auto",
                AgentActivity.created_at >= cutoff,
            ).order_by(AgentActivity.created_at.desc()).limit(20)
        )).scalars().all()
    print(f"\n最近 24hr task_create_auto activities ({len(acts)}):")
    for a in acts:
        e = a.extra or {}
        print(f"  {a.created_at} task_id={e.get('task_id')!s:8} ch={e.get('channel_id')!s:8} "
              f"assignee={e.get('assignee_name')!r} via={e.get('via', 'extract')}")

    # 篩 candidate
    candidates = []
    async with AsyncSessionLocal() as db:
        for a in acts:
            extra = a.extra or {}
            if str(extra.get("channel_id")) != str(target.channel_id):
                print(f"  ✗ {a.id}: channel mismatch ({extra.get('channel_id')} vs {target.channel_id})")
                continue
            tid_str = extra.get("task_id")
            if not tid_str:
                continue
            from uuid import UUID
            try:
                tid = UUID(tid_str)
            except (ValueError, TypeError):
                continue
            t = (await db.execute(select(Task).where(Task.id == tid, Task.deleted_at.is_(None)))).scalar_one_or_none()
            if t is None:
                print(f"  ✗ {a.id}: task missing/deleted")
                continue
            if t.assignee_id != aliu.id:
                print(f"  ✗ {a.id}: task '{t.title[:30]}' assignee={t.assignee_id} != aliu={aliu.id}")
                continue
            candidates.append((t, a))
            print(f"  ✓ candidate: '{t.title[:40]}' (task {tid})")
    print(f"\n候選任務 {len(candidates)} 個")

    # 跑 try_link_acceptance 看
    print("\n>>> 呼叫 try_link_acceptance...")
    await try_link_acceptance(target.id)
    print("\n之後 task_accepted activities:")
    async with AsyncSessionLocal() as db:
        accs = (await db.execute(
            select(AgentActivity).where(AgentActivity.activity_type == "task_accepted")
            .order_by(AgentActivity.created_at.desc()).limit(5)
        )).scalars().all()
    for a in accs:
        print(f"  {a.created_at} {(a.extra or {}).get('task_id')} conf={(a.extra or {}).get('confidence')}")


if __name__ == "__main__":
    asyncio.run(main())
