import type { SportType } from "@/lib/api/matches/types";

// ========================
// Sub-DTOs for MatchPredictionDto
// ========================

export interface MatchInfoDto {
  match_id: string;
  match_name: string;
  home_team: string;
  away_team: string;
  league: string;
  match_date_ms: number;
  league_id?: string | null;
  is_top_league?: boolean;
  // Backtest-derived per-league confidence (ROI + sample size). null = too little data.
  league_confidence?: {
    label: "high" | "medium" | "low";
    bet_roi: number;
    bet_n: number;
    hit: number;
  } | null;
  sport?: SportType;
  // Live snapshot — set when the match is in play (used to detect stale predictions)
  status?: string | null;
  state?: string | null;
  is_live?: boolean;
  current_score_home?: number | null;
  current_score_away?: number | null;
  [key: string]: unknown;
}

export interface PredictionFreshnessDto {
  generated_at_ms: number;
  is_pre_match_snapshot: boolean;
  is_stale_for_live: boolean;
}

export interface SurpriseBreakdownEntryDto {
  code: string;
  points: number;
  label: string;
}

export interface DataQualityDto {
  label: "HIGH" | "MEDIUM" | "LOW";
  score: number;
  home_lineup_count: number;
  away_lineup_count: number;
  lineup_source: string;
  flags: string[];
  [key: string]: unknown;
}

export interface ConfidenceIntervalDto {
  lower: number;
  upper: number;
  width: number;
  band: "HIGH" | "MEDIUM" | "LOW";
  threshold_met: boolean;
}

export interface RiskDto {
  level: "LOW" | "MEDIUM" | "HIGH" | "EXTREME";
  score: number;
  is_surprise_risk: boolean;
  surprise_type: string | null;
  surprise_score?: number;
  surprise_comment?: string | null;
  surprise_reasons?: string[];
  surprise_breakdown?: SurpriseBreakdownEntryDto[];
  warnings: string[];
}

export interface EngineBreakdownDetailEntryDto {
  score: number;
  label: "YUKSEK" | "ORTA" | "DUSUK" | "COK_DUSUK" | string;
  display_name: string;
  interpretation: string;
}

export interface EngineBreakdownDto {
  team: number;
  player: number;
  odds: number;
  referee: number;
  detail?: {
    team?: EngineBreakdownDetailEntryDto;
    player?: EngineBreakdownDetailEntryDto;
    odds?: EngineBreakdownDetailEntryDto;
    referee?: EngineBreakdownDetailEntryDto;
    [key: string]: EngineBreakdownDetailEntryDto | undefined;
  };
  [key: string]: unknown;
}

export type BetGrade = "A" | "B" | "C" | "PASS";
export type SignalTier = "CORE" | "VALUE" | "LEAN" | "LONGSHOT" | "PASS";

export type UnifiedScoreLabel = "very_reliable" | "reliable" | "moderate" | "low";

export interface MatchPickDto {
  market: string;
  pick: string;
  probability: number;
  confidence: number;
  odds: number;
  raw_confidence: number;
  calibrated_confidence: number;
  unified_score?: number;
  unified_score_label?: UnifiedScoreLabel;
  min_required_confidence: number;
  edge: number;
  ev_edge: number;
  implied_prob: number;
  model_probability?: number;
  model_edge?: number;
  calibrated_probability?: number;
  odds_band_probability?: number;
  odds_band_sample?: number;
  odds_band_edge?: number;
  odds_band_aligned?: boolean;
  play_score: number;
  playable: boolean;
  bet_grade: BetGrade;
  stake_units: number;
  decision_reasons: string[];
  confidence_interval?: ConfidenceIntervalDto;
  signal_tier?: SignalTier;
  is_guaranteed?: boolean;
}

export type BettingBrainAction =
  | "BET"
  | "WATCH"
  | "WATCH_NO_VALUE"
  | "REJECT";

export interface BettingBrainEntryDto {
  action: BettingBrainAction;
  score: number;
  summary: string;
  positives: string[];
  issues: string[];
  vetoes: string[];
  sniper_bypassed?: string[];
  trap_market_flag?: boolean;
  trap_market_gap?: number | null;
  model_prob?: number | null;
  implied_prob?: number;
  model_market_gap?: number | null;
  triple_key?: string | null;
  triple_value?: Record<string, unknown> | null;
}

export interface MatchBetAdviceDto {
  playable: boolean;
  suggested_stake_units: number;
  reason: string;
  decision?: "BET" | "WATCHLIST" | "WATCH_NO_VALUE" | "NO_BET" | string;
  confidence_band?: "HIGH" | "MEDIUM" | "LOW";
  min_confidence_for_play?: number;
  signal_tier?: SignalTier;
  [key: string]: unknown;
}

export interface MatchBetSummaryItemDto {
  market: string;
  pick: string;
  raw_confidence: number;
  calibrated_confidence: number;
  unified_score?: number;
  unified_score_label?: UnifiedScoreLabel;
  bet_grade: BetGrade;
  playable: boolean;
  stake_units: number;
  play_score: number;
  ev_edge: number;
  implied_prob: number;
  model_probability?: number;
  model_edge?: number;
  calibrated_probability?: number;
  odds_band_probability?: number;
  odds_band_sample?: number;
  odds_band_edge?: number;
  odds_band_aligned?: boolean;
  odds: number;
  reasons: string[];
  confidence_interval?: ConfidenceIntervalDto;
  signal_tier?: SignalTier;
  // New (post-engine-upgrade)
  is_underdog_reference?: boolean;
  betting_brain?: BettingBrainEntryDto;
}

export interface AggressivePickDto {
  market: string;
  pick: string;
  probability: number;
  confidence: number;
  odds: number | null;
  confidence_interval?: ConfidenceIntervalDto;
}

export interface ScenarioTop5ItemDto {
  score: string;
  prob: number;
}

export interface ScorePredictionDto {
  ft: string;
  ht: string;
  xg_home: number;
  xg_away: number;
  xg_total: number;
}

// ========================
// Main Prediction DTOs
// ========================

export interface MarketBoardEntryDto {
  pick?: string;
  confidence?: number;
  confidence_band?: "HIGH" | "MEDIUM" | "LOW";
  confidence_interval?: ConfidenceIntervalDto;
  playable?: boolean;
  probs?: Record<string, number>;
  [key: string]: unknown;
}

// ========================
// V28 Odds-Band Engine DTOs
// ========================

export interface OddsBandEntryDto {
  win_rate?: number;
  draw_rate?: number;
  lose_rate?: number;
  over_rate?: number;
  under_rate?: number;
  yes_rate?: number;
  no_rate?: number;
  odd_rate?: number;
  even_rate?: number;
  "1x_rate"?: number;
  x2_rate?: number;
  "12_rate"?: number;
  "1x_sample"?: number;
  x2_sample?: number;
  "12_sample"?: number;
  sample: number;
  [key: string]: unknown;
}

export interface OddsBandCardsDto {
  referee_avg: number;
  referee_over_rate: number;
  referee_sample: number;
  team_avg: number;
  team_over_rate: number;
  team_sample: number;
  combined_over_rate: number;
  sample: number;
}

export interface OddsBandHtftComboDto {
  rate: number;
  sample: number;
}

export interface TripleValueEntryDto {
  v27_prob?: number;
  band_rate: number;
  implied_prob: number;
  combined_prob?: number;
  edge: number;
  band_sample: number;
  confirmations?: number;
  is_value: boolean;
}

export type HtftComboKey =
  | "11"
  | "1x"
  | "12"
  | "x1"
  | "xx"
  | "x2"
  | "21"
  | "2x"
  | "22";

export interface V27EngineDto {
  version: string;
  approach?: string;
  consensus?: "AGREE" | "DISAGREE";
  predictions?: Record<string, Record<string, number>>;
  divergence?: Record<string, Record<string, number>>;
  value_edge?: Record<string, Record<string, unknown>>;
  odds_band?: {
    ms_home?: OddsBandEntryDto;
    ms_away?: OddsBandEntryDto;
    ou25?: OddsBandEntryDto;
    ou15?: OddsBandEntryDto;
    ou35?: OddsBandEntryDto;
    btts?: OddsBandEntryDto;
    dc?: OddsBandEntryDto;
    ht_home?: OddsBandEntryDto;
    ht_away?: OddsBandEntryDto;
    ht_ou05?: OddsBandEntryDto;
    ht_ou15?: OddsBandEntryDto;
    oe?: OddsBandEntryDto;
    cards?: OddsBandCardsDto;
    htft?: Record<HtftComboKey, OddsBandHtftComboDto>;
    [key: string]: unknown;
  };
  triple_value?: Record<string, TripleValueEntryDto>;
}

// ========================
// Main Prediction DTOs
// ========================

export interface MatchPredictionDto {
  model_version: string;
  match_info: MatchInfoDto;
  data_quality: DataQualityDto;
  risk: RiskDto;
  engine_breakdown: EngineBreakdownDto;
  main_pick: MatchPickDto | null;
  bet_advice: MatchBetAdviceDto;
  bet_summary: MatchBetSummaryItemDto[];
  supporting_picks: MatchPickDto[];
  aggressive_pick: AggressivePickDto | null;
  scenario_top5: ScenarioTop5ItemDto[];
  score_prediction: ScorePredictionDto;
  market_board: Record<string, MarketBoardEntryDto>;
  reasoning_factors: string[];
  ai_commentary?: string | null;
  v27_engine?: V27EngineDto;
  prediction_freshness?: PredictionFreshnessDto;
  match_commentary?: {
    action?: string;
    headline?: string;
    summary?: string;
    notes?: string[];
    contradictions?: string[];
    confidence_label?: string;
  };
}

export interface ValueBetDto {
  matchId: string;
  matchName: string;
  betType: string;
  prediction: string;
  confidence: number;
  odd: number;
  expectedValue: number;
}

export interface UpcomingPredictionsDto {
  count: number;
  matches: MatchPredictionDto[];
  modelVersion: string;
}

export interface PredictionHistoryStatsDto {
  totalPredictions: number;
  correctPredictions: number;
  accuracy: number;
  [key: string]: unknown;
}

export interface PredictionHistoryResponseDto {
  stats: PredictionHistoryStatsDto;
  history: Record<string, unknown>[];
}

export interface AIHealthDto {
  status: string;
  modelLoaded: boolean;
  predictionServiceReady: boolean;
}

// ========================
// Smart Coupon Request DTO
// ========================

export type CouponStrategy =
  | "SAFE"
  | "BALANCED"
  | "AGGRESSIVE"
  | "VALUE"
  | "MIRACLE";

export interface SmartCouponRequestDto {
  matchIds: string[];
  strategy?: CouponStrategy;
  maxMatches?: number;
  minConfidence?: number;
}

export interface SmartCouponResponseDto {
  coupon: {
    items: Array<{
      matchId: string;
      matchName: string;
      market: string;
      pick: string;
      odd: number;
      confidence: number;
      [key: string]: unknown;
    }>;
    totalOdd: number;
    strategy: CouponStrategy;
    [key: string]: unknown;
  };
  [key: string]: unknown;
}
