// api.ts から分割（挙動不変）: Delegate Observability（D0）。
// ※ 分割に伴い dynamic type import のパスのみ ./lib → ../lib に補正（同一モジュールを指す）。
import { BASE } from './client';

// ── Delegate Observability (D0) ──────────────────────────────────────────
// Task 3 API: GET /api/local/tasks/:id/delegate-runs
//             GET /api/local/tasks/:id/delegate-runs/:runId/timeline

/** Lightweight event record returned by the delegate-run timeline endpoint. */
export interface TraceEventLite {
  eventId: string;
  ts: string;
  seq: number;
  kind: string;
  movement?: string;
  iteration?: number;
  payload: unknown;
}

export async function fetchDelegateRuns(taskId: number): Promise<import('../lib/delegateRuns').DelegateRunsResult> {
  const res = await fetch(`${BASE}/local/tasks/${taskId}/delegate-runs`);
  if (!res.ok) throw new Error(`fetchDelegateRuns failed: ${res.status}`);
  const body = await res.json();
  return { runs: body.runs ?? [], subtasks: body.subtasks ?? [] };
}

export async function fetchDelegateRunTimeline(taskId: number, delegateRunId: string, jobId?: string): Promise<TraceEventLite[]> {
  const q = jobId ? `?jobId=${encodeURIComponent(jobId)}` : '';
  const res = await fetch(`${BASE}/local/tasks/${taskId}/delegate-runs/${encodeURIComponent(delegateRunId)}/timeline${q}`);
  if (!res.ok) throw new Error(`fetchDelegateRunTimeline failed: ${res.status}`);
  return (await res.json()).events ?? [];
}
