"""快照系統狀態。"""
import sys, os
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")

import asyncio
from datetime import datetime, timedelta, timezone
from sqlalchemy import select, func
from app.database import AsyncSessionLocal
from app.models.task import Task
from app.models.user import User
from app.models.channel import Message
from app.models.agent_activity import AgentActivity


async def main():
    async with AsyncSessionLocal() as db:
        # 任務統計
        total = (await db.execute(select(func.count()).select_from(Task).where(Task.deleted_at.is_(None)))).scalar()
        done = (await db.execute(select(func.count()).select_from(Task).where(Task.deleted_at.is_(None), Task.status == "done"))).scalar()
        in_progress = (await db.execute(select(func.count()).select_from(Task).where(Task.deleted_at.is_(None), Task.status == "in_progress"))).scalar()
        todo = (await db.execute(select(func.count()).select_from(Task).where(Task.deleted_at.is_(None), Task.status == "todo"))).scalar()
        users = (await db.execute(select(func.count()).select_from(User).where(User.deleted_at.is_(None), User.is_active.is_(True)))).scalar()

        # 過去 2 小時 activity
        cutoff = datetime.now(timezone.utc) - timedelta(hours=2)
        rows = (await db.execute(
            select(AgentActivity.activity_type, func.count(), func.sum(AgentActivity.cost_usd))
            .where(AgentActivity.created_at >= cutoff)
            .group_by(AgentActivity.activity_type)
        )).all()

        # 過去 24 小時的 cost 加總
        cutoff_24 = datetime.now(timezone.utc) - timedelta(hours=24)
        cost_24 = (await db.execute(
            select(func.sum(AgentActivity.cost_usd))
            .where(AgentActivity.created_at >= cutoff_24, AgentActivity.cost_usd.is_not(None))
        )).scalar() or 0

        # 體悟筆記累積
        reflections = (await db.execute(
            select(func.count()).select_from(AgentActivity).where(AgentActivity.activity_type == "reflection_note")
        )).scalar()
        # 認領狀態
        accepted = (await db.execute(
            select(func.count()).select_from(AgentActivity).where(AgentActivity.activity_type == "task_accepted")
        )).scalar()
        auto_created = (await db.execute(
            select(func.count()).select_from(AgentActivity).where(AgentActivity.activity_type == "task_create_auto")
        )).scalar()

        # 過去 24h 訊息數
        msg_24h = (await db.execute(
            select(func.count()).select_from(Message)
            .where(Message.created_at >= cutoff_24, Message.deleted_at.is_(None))
        )).scalar()

    print(f"=== 任務看板 ===")
    print(f"  使用者(活躍): {users}")
    print(f"  任務總數: {total}  (todo={todo} / in_progress={in_progress} / done={done})")
    print()
    print(f"=== Cooper 累積總計 ===")
    print(f"  自動建任務: {auto_created}")
    print(f"  認領記錄: {accepted}")
    print(f"  體悟筆記: {reflections}")
    print()
    print(f"=== 過去 2 小時 activity ===")
    for at, cnt, cost in rows:
        cost_str = f"${cost:.4f}" if cost else "-"
        print(f"  {at:30s} {cnt:>4d}  {cost_str}")
    print()
    print(f"=== 過去 24 小時總成本: ${cost_24:.4f}")
    print(f"=== 過去 24 小時訊息數: {msg_24h}")


asyncio.run(main())
