export let BASE_URL = 'http://localhost:8080';

export function setBaseUrl(url: string): void {
  // Trim trailing slash for consistency
  BASE_URL = url.replace(/\/$/, '');
}

export interface Stats {
  total_requests: number;
  matched_requests: number;
  tokens_saved: number;
  estimated_cost_saved_usd: number;
  avg_saving_pct: number;
  saving_ratio: number;
}

export interface Script {
  id: string;
  name: string;
  description: string;
  tags: string[];
  version: string;
  usage_count: number;
  avg_saving_pct: number;
}

export interface PendingEvent {
  id: string;
  timestamp: string;
  skill_id: string | null;
  saving_pct: number | null;
  latency_ms: number | null;
  status: string;
}

async function apiFetch<T>(path: string): Promise<T> {
  const response = await fetch(`${BASE_URL}${path}`, {
    headers: { 'Accept': 'application/json' },
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }
  return response.json() as Promise<T>;
}

export async function fetchStats(): Promise<Stats> {
  return apiFetch<Stats>('/bibividi/api/stats');
}

export async function fetchScripts(): Promise<Script[]> {
  return apiFetch<Script[]>('/bibividi/api/scripts');
}

export async function fetchPending(): Promise<PendingEvent[]> {
  return apiFetch<PendingEvent[]>('/bibividi/api/pending');
}
