/**
 * AI 监控后台 API
 *
 * 对接后端 /api/admin/ai/* 端点，提供 Dashboard、调度任务、调用记录、
 * 缓存管理、Token 预算、批量执行、告警管理等功能。
 */

import { apiClient } from "./client";

// ---- 类型定义 ----

// Dashboard
export interface DailyTrend {
  date: string;
  calls: number;
  success_rate: number;
}

export interface AppDistItem {
  app_type: string;
  count: number;
  percentage: number;
}

export interface BudgetInfo {
  daily_used: number;
  daily_limit: number;
  daily_pct: number;
  monthly_used: number;
  monthly_limit: number;
  monthly_pct: number;
}

export interface AlertItem {
  id: number;
  app_type: string;
  status: string;
  alert_status: string | null;
  error_message: string | null;
  created_at: string;
}

export interface AppHealthItem {
  app_type: string;
  last_status: string | null;
  last_call_at: string | null;
}

export interface DashboardResponse {
  today_calls: number;
  today_success_rate: number;
  today_tokens: number;
  today_avg_latency_ms: number;
  trend_7d: DailyTrend[];
  app_distribution: AppDistItem[];
  budget: BudgetInfo;
  recent_alerts: AlertItem[];
  app_health: AppHealthItem[];
}

// 调度任务
export interface TriggerJobItem {
  id: number;
  event_type: string;
  member_id: number | null;
  status: string;
  app_chain: string | null;
  is_forced: boolean;
  site_id: number;
  started_at: string | null;
  finished_at: string | null;
  created_at: string;
}

export interface TriggerJobDetailResponse extends TriggerJobItem {
  payload: Record<string, unknown> | null;
  error_message: string | null;
  connector_type: string;
}

export interface TriggerJobListResponse {
  items: TriggerJobItem[];
  total: number;
  page: number;
  page_size: number;
  today_skipped_duplicates: number;
}

export interface RetryResponse {
  trigger_job_id: number;
  status: string;
}

export interface TriggerJobQuery {
  event_type?: string;
  status?: string;
  site_id?: number;
  date_from?: string;
  date_to?: string;
  page?: number;
  page_size?: number;
}

// 调用记录
export interface RunLogItem {
  id: number;
  app_type: string;
  trigger_type: string;
  member_id: number | null;
  tokens_used: number;
  latency_ms: number | null;
  status: string;
  site_id: number;
  created_at: string;
}

export interface RunLogDetailResponse extends RunLogItem {
  request_prompt: string | null;
  response_text: string | null;
  error_message: string | null;
  session_id: string | null;
  finished_at: string | null;
}

export interface RunLogListResponse {
  items: RunLogItem[];
  total: number;
  page: number;
  page_size: number;
}

export interface RunLogQuery {
  app_type?: string;
  status?: string;
  trigger_type?: string;
  site_id?: number;
  date_from?: string;
  date_to?: string;
  page?: number;
  page_size?: number;
}

// 缓存管理
export interface CacheInvalidateReq {
  site_id: number;
  app_type?: string;
  member_id?: number;
}

export interface CacheInvalidateResponse {
  affected_count: number;
}

// Token 预算
export interface BudgetResponse {
  daily_used: number;
  daily_limit: number;
  daily_pct: number;
  monthly_used: number;
  monthly_limit: number;
  monthly_pct: number;
}

// 批量执行
export interface BatchRunReq {
  app_types: string[];
  member_ids: number[];
  site_id: number;
}

export interface BatchRunEstimate {
  batch_id: string;
  estimated_calls: number;
  estimated_tokens: number;
}

export interface BatchRunConfirmResponse {
  status: string;
}

// 告警
export interface AlertQuery {
  alert_status?: string;
  site_id?: number;
  page?: number;
  page_size?: number;
}

export interface AlertListResponse {
  items: AlertItem[];
  total: number;
  page: number;
  page_size: number;
}

export interface AlertActionResponse {
  id: number;
  alert_status: string;
}

// ---- API 调用 ----

// Dashboard
export async function getDashboard(siteId?: number): Promise<DashboardResponse> {
  const { data } = await apiClient.get<DashboardResponse>("/admin/ai/dashboard", {
    params: siteId != null ? { site_id: siteId } : undefined,
  });
  return data;
}

// 调度任务
export async function getTriggerJobs(params: TriggerJobQuery): Promise<TriggerJobListResponse> {
  const { data } = await apiClient.get<TriggerJobListResponse>("/admin/ai/trigger-jobs", { params });
  return data;
}

export async function getTriggerJobDetail(id: number): Promise<TriggerJobDetailResponse> {
  const { data } = await apiClient.get<TriggerJobDetailResponse>(`/admin/ai/trigger-jobs/${id}`);
  return data;
}

export async function retryTriggerJob(id: number): Promise<RetryResponse> {
  const { data } = await apiClient.post<RetryResponse>(`/admin/ai/trigger-jobs/${id}/retry`);
  return data;
}

// 调用记录
export async function getRunLogs(params: RunLogQuery): Promise<RunLogListResponse> {
  const { data } = await apiClient.get<RunLogListResponse>("/admin/ai/run-logs", { params });
  return data;
}

export async function getRunLogDetail(id: number): Promise<RunLogDetailResponse> {
  const { data } = await apiClient.get<RunLogDetailResponse>(`/admin/ai/run-logs/${id}`);
  return data;
}

// 缓存管理
export async function invalidateCache(body: CacheInvalidateReq): Promise<CacheInvalidateResponse> {
  const { data } = await apiClient.post<CacheInvalidateResponse>("/admin/ai/cache/invalidate", body);
  return data;
}

// Token 预算
export async function getBudget(): Promise<BudgetResponse> {
  const { data } = await apiClient.get<BudgetResponse>("/admin/ai/budget");
  return data;
}

// 批量执行
export async function createBatchRun(body: BatchRunReq): Promise<BatchRunEstimate> {
  const { data } = await apiClient.post<BatchRunEstimate>("/admin/ai/batch-run", body);
  return data;
}

export async function confirmBatchRun(batchId: string): Promise<BatchRunConfirmResponse> {
  const { data } = await apiClient.post<BatchRunConfirmResponse>("/admin/ai/batch-run/confirm", {
    batch_id: batchId,
  });
  return data;
}

// 告警
export async function getAlerts(params: AlertQuery): Promise<AlertListResponse> {
  const { data } = await apiClient.get<AlertListResponse>("/admin/ai/alerts", { params });
  return data;
}

export async function ackAlert(id: number): Promise<AlertActionResponse> {
  const { data } = await apiClient.post<AlertActionResponse>(`/admin/ai/alerts/${id}/ack`);
  return data;
}

export async function ignoreAlert(id: number): Promise<AlertActionResponse> {
  const { data } = await apiClient.post<AlertActionResponse>(`/admin/ai/alerts/${id}/ignore`);
  return data;
}
