"""
Agent 活動相關 API(階段 7-A)。

  GET  /api/agent/activity            ─ 拉 24 小時 / 7 天的 庫柏動態 stats + timeline
  GET  /api/agent/activity/timeline   ─ 拉最近 N 筆動作明細
"""

from __future__ import annotations

from datetime import datetime, timedelta, timezone

from fastapi import APIRouter, Query
from sqlalchemy import desc, func, select

from app.core.deps import CurrentUser, DBSession
from app.models.agent_activity import AgentActivity


router = APIRouter(prefix="/api/agent", tags=["agent"])


@router.get("/activity", summary="庫柏動態統計(24 小時 / 7 天)")
async def get_activity_stats(current_user: CurrentUser, db: DBSession):
    """聚合最近 24 小時 / 7 天的 Agent 活動。
    給 dashboard「庫柏動態」面板用。
    """
    now = datetime.now(timezone.utc)
    h24 = now - timedelta(hours=24)
    d7 = now - timedelta(days=7)

    async def _agg(since):
        rows = (await db.execute(
            select(
                AgentActivity.activity_type,
                func.count().label("cnt"),
                func.coalesce(func.sum(AgentActivity.cost_usd), 0.0).label("cost"),
            )
            .where(AgentActivity.created_at >= since)
            .group_by(AgentActivity.activity_type)
        )).all()
        return {r.activity_type: {"count": r.cnt, "cost_usd": float(r.cost or 0)} for r in rows}

    by_24h = await _agg(h24)
    by_7d = await _agg(d7)

    def _total_cost(d):
        return round(sum(v["cost_usd"] for v in d.values()), 4)

    return {
        "h24": {
            "by_type": by_24h,
            "total_cost_usd": _total_cost(by_24h),
            "total_count": sum(v["count"] for v in by_24h.values()),
        },
        "d7": {
            "by_type": by_7d,
            "total_cost_usd": _total_cost(by_7d),
            "total_count": sum(v["count"] for v in by_7d.values()),
        },
    }


@router.get("/reflections", summary="團隊體悟列表(過去 N 天)")
async def list_reflections(
    current_user: CurrentUser,
    db: DBSession,
    days: int = Query(default=30, ge=1, le=365),
    user_id: str | None = Query(default=None, description="只看某位 user 的體悟"),
):
    """供工作台「💡 體悟」view 用。回 [{message_id, by, summary, raw, tag, actionable, similar_count, created_at}]。"""
    from datetime import datetime, timedelta, timezone
    from app.models.user import User
    from sqlalchemy import select as _select
    cutoff = datetime.now(timezone.utc) - timedelta(days=days)
    stmt = select(AgentActivity).where(
        AgentActivity.activity_type == "reflection_note",
        AgentActivity.created_at >= cutoff,
    ).order_by(desc(AgentActivity.created_at))
    if user_id:
        try:
            from uuid import UUID as _UUID
            stmt = stmt.where(AgentActivity.user_id == _UUID(user_id))
        except (ValueError, TypeError):
            pass
    rows = (await db.execute(stmt)).scalars().all()
    # 撈 user 名字
    uids = list({r.user_id for r in rows if r.user_id})
    users_map = {}
    if uids:
        us = (await db.execute(_select(User).where(User.id.in_(uids)))).scalars().all()
        users_map = {u.id: u.display_name for u in us}
    return [
        {
            "id": str(r.id),
            "message_id": (r.extra or {}).get("message_id"),
            "by": users_map.get(r.user_id, "(未知)") if r.user_id else "(系統)",
            "by_id": str(r.user_id) if r.user_id else None,
            "summary": (r.extra or {}).get("summary") or r.summary,
            "raw": (r.extra or {}).get("raw") or "",
            "tag": (r.extra or {}).get("tag"),
            "actionable": (r.extra or {}).get("actionable", False),
            "similar_count": (r.extra or {}).get("similar_count", 0),
            "similar_to": (r.extra or {}).get("similar_to") or [],
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in rows
    ]


@router.get("/activity/timeline", summary="庫柏動作時間軸(最近 N 筆)")
async def get_activity_timeline(
    current_user: CurrentUser,
    db: DBSession,
    limit: int = Query(default=30, le=200),
    types: str | None = Query(default=None, description="逗號分隔過濾 type"),
):
    stmt = select(AgentActivity).order_by(desc(AgentActivity.created_at)).limit(limit)
    if types:
        type_list = [t.strip() for t in types.split(",") if t.strip()]
        if type_list:
            stmt = stmt.where(AgentActivity.activity_type.in_(type_list))
    rows = (await db.execute(stmt)).scalars().all()
    return [
        {
            "id": str(r.id),
            "type": r.activity_type,
            "summary": r.summary,
            "user_id": str(r.user_id) if r.user_id else None,
            "success": r.success,
            "cost_usd": r.cost_usd,
            "duration_ms": r.duration_ms,
            "extra": r.extra,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in rows
    ]
