// api.ts から分割（挙動不変）: LLM usage ダッシュボード v2。
import { BASE } from './client';

// ============================================================
// LLM usage dashboard v2 (per-user, multi-axis group-by + local timezone).
// Spec: docs/superpowers/specs/2026-06-11-usage-dashboard-v2-design.md
export interface UsageCounters {
  tokensIn: number;
  tokensOut: number;
  requests: number;
}
export type UsageGroupBy = 'source' | 'model' | 'route' | 'user' | 'org';

/** One time bucket: a per-series-key map of counters. Keys come from `keys`. */
export interface UsageBucket {
  bucket: string;            // 'YYYY-MM-DD' | 'YYYY-Www' | 'YYYY-MM'
  segments: Record<string, UsageCounters>;
}
export interface UsageByUser extends UsageCounters {
  userId: string;
  /** Resolved display name (real users); 'local' / 'system' for sentinels. */
  displayName: string;
}
export interface UsageDailyResponse {
  from: string;
  to: string;
  granularity: 'hour' | 'day' | 'week' | 'month';
  groupBy: UsageGroupBy;
  tzOffset: number;
  scope: 'all' | 'self';
  /** Ordered series keys (legend/palette order). */
  keys: string[];
  /** Human labels for keys (only populated for groupBy=user; else key=label). */
  labels: Record<string, string>;
  series: UsageBucket[];
  totals: Record<string, UsageCounters>;
  byUser?: UsageByUser[];   // admin / local mode only
}

export async function getUsageDaily(params: {
  from?: string;
  to?: string;
  granularity?: 'hour' | 'day' | 'week' | 'month';
  groupBy?: UsageGroupBy;
  tzOffset?: number;
}): Promise<UsageDailyResponse> {
  const qs = new URLSearchParams();
  if (params.from) qs.set('from', params.from);
  if (params.to) qs.set('to', params.to);
  if (params.granularity) qs.set('granularity', params.granularity);
  if (params.groupBy) qs.set('groupBy', params.groupBy);
  if (params.tzOffset !== undefined) qs.set('tzOffset', String(params.tzOffset));
  const q = qs.toString();
  const res = await fetch(`${BASE}/usage/daily${q ? `?${q}` : ''}`);
  if (!res.ok) throw new Error(`Failed to load usage (${res.status})`);
  return res.json();
}
