import client from './client';
import type { PaginatedResponse } from './types';

// --- Types ---

export type InsightType = 'risk_score' | 'anomaly' | 'follow_up_hint' | 'consult_hint';
export type InsightSource = 'rule' | 'llm' | 'hybrid';
export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';

export interface MatchedRule {
  rule_id: string;
  name: string;
  score: number;
  severity: string;
  suggestion?: string;
}

export interface RiskScore {
  score: number;
  level: RiskLevel;
  matched_rules: MatchedRule[];
}

export interface CopilotInsight {
  id: string;
  patient_id: string;
  insight_type: InsightType;
  source: InsightSource;
  severity: 'info' | 'warning' | 'critical';
  title: string;
  content: Record<string, unknown>;
  rule_matches?: MatchedRule[];
  llm_supplement?: string;
  created_at: string;
}

// --- API Functions ---

export async function getPatientRisk(patientId: string) {
  const { data } = await client.get<{ success: boolean; data: RiskScore }>(`/copilot/patients/${patientId}/risk`);
  return data.data;
}

export async function listInsights(params: {
  patient_id?: string;
  insight_type?: string;
  severity?: string;
  page?: number;
  page_size?: number;
}) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<CopilotInsight> }>('/copilot/insights', { params });
  return data.data;
}

export function dismissInsight(id: string) {
  return client.post(`/copilot/insights/${id}/dismiss`);
}

export function listAlerts(params?: { severity?: string; page?: number; page_size?: number }) {
  return listInsights({ insight_type: 'anomaly', ...params });
}

export async function listRules(params?: { page?: number; page_size?: number }) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<Record<string, unknown>> }>('/copilot/rules', { params });
  return data.data;
}
