import client from '../client';

export interface UsageOverview {
  total_count: number;
}

export interface TypeDistribution {
  analysis_type: string;
  count: number;
}

export interface ProviderInfo {
  id: string;
  name: string;
  provider_type: string;
  is_active: boolean;
  model_name?: string;
}

export interface ProviderHealth {
  provider_id: string;
  status: string;
  latency_ms?: number;
  last_checked_at?: string;
}

export interface QuotaSummary {
  provider_id: string;
  quota_limit: number;
  quota_used: number;
  quota_remaining: number;
  period: string;
}

export interface BudgetStatus {
  total_budget: number;
  spent: number;
  remaining: number;
  period: string;
}

export interface CostEstimate {
  analysis_type: string;
  estimated_cost: number;
  currency: string;
}

export interface DailyUsageRow {
  date: string;
  feature: string;
  provider: string;
  model: string;
  total_calls: number;
  total_input_tokens: number;
  total_output_tokens: number;
  total_cost_cents: number;
}

export interface FeatureFlag {
  feature: string;
  is_enabled: boolean;
}

export const usageApi = {
  overview: async () => {
    const resp = await client.get('/ai/usage/overview');
    return resp.data.data as UsageOverview;
  },
  byType: async () => {
    const resp = await client.get('/ai/usage/by-type');
    return resp.data.data as TypeDistribution[];
  },
  listProviders: async () => {
    const resp = await client.get('/ai/providers');
    return resp.data.data as ProviderInfo[];
  },
  getProvidersHealth: async () => {
    const resp = await client.get('/ai/providers/health');
    return resp.data.data as ProviderHealth[];
  },
  getQuotaSummary: async () => {
    const resp = await client.get('/ai/quota/summary');
    return resp.data.data as QuotaSummary[];
  },
  getBudgetStatus: async () => {
    const resp = await client.get('/ai/budget/status');
    return resp.data.data as BudgetStatus;
  },
  getCostEstimate: async (params: { analysis_type: string }) => {
    const resp = await client.get('/ai/cost/estimate', { params });
    return resp.data.data as CostEstimate;
  },
  getDailyUsage: async (startDate: string, endDate: string) => {
    const resp = await client.get('/ai/admin/daily-usage', {
      params: { start_date: startDate, end_date: endDate },
    });
    return resp.data.data as DailyUsageRow[];
  },
  getFeatureFlags: async () => {
    const resp = await client.get('/ai/admin/flags');
    return resp.data.data as FeatureFlag[];
  },
  updateFeatureFlag: async (feature: string, enabled: boolean) => {
    const resp = await client.post('/ai/admin/flags', { feature, enabled });
    return resp.data.data as { feature: string; enabled: boolean };
  },
};
