const API_BASE = '/api/v1';

async function fetchApi<T>(path: string, options?: RequestInit): Promise<T> {
  const token = localStorage.getItem('dd0c_token') || '';
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
      ...options?.headers,
    },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({ error: res.statusText }));
    throw new Error(body.error || res.statusText);
  }
  return res.json();
}

// --- Types ---

export interface AnalyticsSummary {
  total_requests: number;
  total_cost_original: number;
  total_cost_actual: number;
  total_cost_saved: number;
  savings_pct: number;
  avg_latency_ms: number;
  p99_latency_ms: number;
  routing_decisions: {
    passthrough: number;
    cheapest: number;
    cascading: number;
  };
}

export interface TimeseriesPoint {
  bucket: string;
  request_count: number;
  cost_saved: number;
  avg_latency_ms: number;
}

export interface ModelBreakdown {
  model: string;
  request_count: number;
  total_tokens: number;
  total_cost: number;
}

export interface RoutingRule {
  id?: string;
  priority: number;
  name: string;
  match_model?: string;
  match_feature?: string;
  match_team?: string;
  match_complexity?: string;
  strategy: string;
  target_model?: string;
  target_provider?: string;
  fallback_models?: string[];
  enabled: boolean;
}

export interface ApiKey {
  id: string;
  name: string;
  key_prefix: string;
  scopes: string[];
  last_used_at?: string;
  created_at: string;
}

export interface ApiKeyCreated {
  id: string;
  key: string;
  name: string;
}

export interface OrgInfo {
  id: string;
  name: string;
  slug: string;
  tier: string;
}

// --- API calls ---

export const api = {
  getSummary: () => fetchApi<AnalyticsSummary>('/analytics/summary'),
  getTimeseries: (interval = 'hour') =>
    fetchApi<TimeseriesPoint[]>(`/analytics/timeseries?interval=${interval}`),
  getModels: () => fetchApi<ModelBreakdown[]>('/analytics/models'),

  listRules: () => fetchApi<RoutingRule[]>('/rules'),
  createRule: (rule: RoutingRule) =>
    fetchApi<RoutingRule>('/rules', { method: 'POST', body: JSON.stringify(rule) }),
  updateRule: (id: string, rule: RoutingRule) =>
    fetchApi<void>(`/rules/${id}`, { method: 'PUT', body: JSON.stringify(rule) }),
  deleteRule: (id: string) =>
    fetchApi<void>(`/rules/${id}`, { method: 'DELETE' }),

  listKeys: () => fetchApi<ApiKey[]>('/keys'),
  createKey: (name: string) =>
    fetchApi<ApiKeyCreated>('/keys', { method: 'POST', body: JSON.stringify({ name }) }),
  revokeKey: (id: string) =>
    fetchApi<void>(`/keys/${id}`, { method: 'DELETE' }),

  getOrg: () => fetchApi<OrgInfo>('/org'),
};
