-- dashboard.sql: run-history dashboard 读模型（只读聚合）。
--   - SessionTimeline: 单会话的 RPC 事件按 (direction, rpc_kind, method) 分桶，
--     给出条数 + 首/末时间戳，用于会话时间线概览。
--   - SessionRollup: 在 owner/admin scope + 可选 project/requirement 过滤下，
--     统计会话总数、成功率（exited 视为成功）、总成本、平均时长。
--   - SessionsByDay: 按天的 总数 / 成功 / 失败 / 成本 时间序列。
-- scope 约定（与 ListSessionsByUser/ListAllSessions 一致）：
--   $1 user_id 为 NULL 时不按用户过滤（admin 全量），非 NULL 时仅该用户。

-- name: SessionTimeline :many
-- 单会话事件时间线：按 method/kind 分桶聚合（条数 + 首末时间）。
SELECT direction,
       rpc_kind,
       COALESCE(method, '')                AS method,
       COUNT(*)::bigint                    AS event_count,
       MIN(created_at)::timestamptz        AS first_at,
       MAX(created_at)::timestamptz        AS last_at
FROM acp_events
WHERE session_id = $1
GROUP BY direction, rpc_kind, COALESCE(method, '')
ORDER BY first_at ASC;

-- name: SessionRollup :one
-- owner/admin scope + 可选 project/requirement + 时间窗内的会话汇总。
-- success = status='exited'；avg_duration_seconds 仅统计已结束（ended_at 非空）会话。
SELECT
  COUNT(*)::bigint                                                            AS total,
  COUNT(*) FILTER (WHERE status = 'exited')::bigint                           AS succeeded,
  COUNT(*) FILTER (WHERE status = 'crashed')::bigint                          AS crashed,
  COUNT(*) FILTER (WHERE status IN ('starting','running'))::bigint            AS active,
  COALESCE(SUM(cost_usd), 0)::numeric                                         AS total_cost_usd,
  COALESCE(SUM(tokens_total), 0)::bigint                                      AS total_tokens,
  COALESCE(
    AVG(EXTRACT(EPOCH FROM (ended_at - started_at)))
      FILTER (WHERE ended_at IS NOT NULL),
    0)::float8                                                                AS avg_duration_seconds
FROM acp_sessions
WHERE ($1::uuid IS NULL OR user_id = $1)
  AND ($2::uuid IS NULL OR project_id = $2)
  AND ($3::uuid IS NULL OR requirement_id = $3)
  AND started_at >= $4
  AND started_at < $5;

-- name: SessionsByDay :many
-- 按天的会话时间序列（总数 / 成功 / 失败 / 成本），同 SessionRollup 的 scope。
SELECT
  date_trunc('day', started_at)::timestamptz                        AS day,
  COUNT(*)::bigint                                                  AS total,
  COUNT(*) FILTER (WHERE status = 'exited')::bigint                 AS succeeded,
  COUNT(*) FILTER (WHERE status = 'crashed')::bigint                AS crashed,
  COALESCE(SUM(cost_usd), 0)::numeric                               AS total_cost_usd
FROM acp_sessions
WHERE ($1::uuid IS NULL OR user_id = $1)
  AND ($2::uuid IS NULL OR project_id = $2)
  AND ($3::uuid IS NULL OR requirement_id = $3)
  AND started_at >= $4
  AND started_at < $5
GROUP BY day
ORDER BY day ASC;
