import { api } from "./client";

export type FormulaCondition = { field: string; op: string; value: unknown };
export type FormulaScore = { field: string; weight: number; direction: "asc" | "desc" };
export type ScreenerFormula = {
  universe: { exclude_st: boolean; listed_days_min: number };
  filters: FormulaCondition[];
  score: FormulaScore[];
  limit: number;
  min_score: number;
  meta?: Record<string, string>;
};
export type ScreenerStrategy = {
  id: string;
  version: number;
  kind: "stage" | "curated";
  name: string;
  display_name: string;
  description: string;
  regimes: string[];
  formula: ScreenerFormula;
};
export type Candidate = {
  identifier: string;
  code: string;
  name: string;
  sector: string;
  close: number | null;
  pct_chg: number | null;
  amount_billion: number | null;
  score_display: number;
  reason: string;
  risk_flags: string[];
  historical_estimate?: number | null;
};
export type ScreenerBacktest = {
  sample_size: number;
  evaluated_dates: number;
  stable: boolean;
  win_rate: number | null;
  average_return_3d: number | null;
  period_start: string | null;
  period_end: string | null;
  message: string;
};
export type ScreenerRun = {
  id: number;
  mode: "stage" | "curated" | "custom";
  strategy_id: string;
  strategy_name: string;
  selection_date: string;
  status: "pending" | "running" | "completed" | "no_signal" | "data_incomplete" | "failed";
  coverage: number;
  missing_fields: string[];
  items: Candidate[];
  error_message: string;
  backtest?: ScreenerBacktest | null;
};
export type CustomStrategy = {
  id: number;
  name: string;
  version: number;
  formula: ScreenerFormula;
};
export type ScreenerCatalog = {
  factor_groups: Record<string, string[]>;
  factors: Record<string, string>;
  stage: ScreenerStrategy[];
  curated: ScreenerStrategy[];
};
export type ScreenerWorkspace = {
  trade_date: string | null;
  message: string;
  catalog: ScreenerCatalog;
  stage_runs: ScreenerRun[];
  curated_runs: ScreenerRun[];
  custom_strategies: CustomStrategy[];
  custom_runs: ScreenerRun[];
};
export type StrategyTrack = {
  id: number;
  identifier: string;
  code: string;
  name: string;
  sector: string;
  selection_date: string;
  strategy_name: string;
  entry_price: number;
  t1_open_return: number | null;
  t1_return: number | null;
  t3_return: number | null;
  t5_return: number | null;
  max_gain: number | null;
  max_drawdown: number | null;
  observed_days: number;
};

export const screenerApi = {
  catalog(): Promise<ScreenerCatalog> {
    return api.get("/screener/catalog");
  },
  workspace(date: string): Promise<ScreenerWorkspace> {
    return api.get(`/screener?date=${encodeURIComponent(date)}`);
  },
  compileFormula(description: string): Promise<{ formula: ScreenerFormula; prompt_version: string }> {
    return api.post("/screener/formula/compile", { description });
  },
  saveCustom(name: string, formula: ScreenerFormula): Promise<CustomStrategy> {
    return api.put("/screener/custom", { name, formula });
  },
  deleteCustom(id: number): Promise<{ message: string }> {
    return api.delete(`/screener/custom/${id}`);
  },
  runCustom(id: number, date: string): Promise<ScreenerRun> {
    return api.post(`/screener/custom/${id}/run?date=${encodeURIComponent(date)}`);
  },
  tracks(): Promise<StrategyTrack[]> {
    return api.get("/screener/tracks");
  },
  addTrack(runId: number, identifier: string): Promise<{ id: number }> {
    return api.post("/screener/tracks", { run_id: runId, identifier });
  },
  removeTrack(id: number): Promise<{ message: string }> {
    return api.delete(`/screener/tracks/${id}`);
  },
};
