const BASE = '';

export interface Stats {
  total_sessions: number;
  total_messages: number;
  by_source: { source: string; count: number }[];
  by_type: { msg_type: string; count: number }[];
  tokens: { input: number; output: number; cached: number; thinking: number };
}

export interface Session {
  id: string;
  source: string;
  model: string | null;
  first_seen: string;
  last_updated: string;
  message_count: number;
  latest_message: string | null;
  user_email: string | null;
  user_name: string | null;
  device_name: string | null;
  cwd: string | null;
  repo_url: string | null;
  repo_name: string | null;
  git_branch: string | null;
  git_commit: string | null;
  project_hash: string | null;
  org: string | null;
}

export interface Message {
  id: string;
  session_id: string;
  source: string;
  msg_type: string;
  timestamp: string;
  content: string | null;
  content_preview?: string | null;
  thinking: string | null;
  model: string | null;
  raw_line_number: number | null;
  input_tokens: number | null;
  output_tokens: number | null;
  cached_tokens: number | null;
  thinking_tokens: number | null;
  tool_name: string | null;
  tool_input: unknown | null;
  tool_output: string | null;
  tool_status: string | null;
}

export type FeedMessage = Pick<
  Message,
  'id' | 'session_id' | 'source' | 'msg_type' | 'timestamp' | 'model' | 'input_tokens' | 'output_tokens'
> & { content_preview: string | null };

async function get<T>(path: string): Promise<T> {
  const res = await fetch(`${BASE}${path}`);
  if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
  return res.json();
}

export const api = {
  health: () => get<{ status: string; db: string }>('/health'),
  stats: () => get<Stats>('/api/stats'),
  sessions: (params?: { source?: string; limit?: number; offset?: number }) => {
    const q = new URLSearchParams();
    if (params?.source) q.set('source', params.source);
    if (params?.limit) q.set('limit', String(params.limit));
    if (params?.offset) q.set('offset', String(params.offset));
    const qs = q.toString();
    return get<Session[]>(`/api/sessions${qs ? '?' + qs : ''}`);
  },
  session: (id: string) =>
    get<Session[]>(`/api/sessions?id=${encodeURIComponent(id)}&limit=1`).then(
      (rows) => rows[0] ?? null,
    ),
  messages: (sessionId: string, params?: { limit?: number; offset?: number }) => {
    const q = new URLSearchParams({ session_id: sessionId });
    if (params?.limit) q.set('limit', String(params.limit));
    if (params?.offset) q.set('offset', String(params.offset));
    return get<Message[]>(`/api/messages?${q}`);
  },
  feed: (params?: { since?: string; limit?: number }) => {
    const q = new URLSearchParams();
    if (params?.since) q.set('since', params.since);
    if (params?.limit) q.set('limit', String(params.limit));
    return get<FeedMessage[]>(`/api/feed?${q}`);
  },
};
