import { generateOllamaText } from "./ollama-client";

interface PredictionData {
  match_info?: Record<string, unknown>;
  score_prediction?: Record<string, unknown>;
  market_board?: Record<string, unknown>;
  risk?: Record<string, unknown>;
  bet_advice?: Record<string, unknown>;
  scenario_top5?: Array<{ score: string; prob: number }>;
  v27_engine?: Record<string, unknown>;
  data_quality?: Record<string, unknown>;
}

function buildPrompt(p: PredictionData): string {
  const mi = (p.match_info ?? {}) as Record<string, unknown>;
  const sp = (p.score_prediction ?? {}) as Record<string, unknown>;
  const mb = (p.market_board ?? {}) as Record<string, unknown>;
  const risk = (p.risk ?? {}) as Record<string, unknown>;
  const ba = (p.bet_advice ?? {}) as Record<string, unknown>;
  const dq = (p.data_quality ?? {}) as Record<string, unknown>;
  const v27 = (p.v27_engine ?? {}) as Record<string, unknown>;

  const home = String(mi.home_team ?? "Ev Sahibi");
  const away = String(mi.away_team ?? "Deplasman");
  const league = String(mi.league ?? "");

  // Market board - ham olasılıklar
  const ms = (mb.MS ?? {}) as Record<string, unknown>;
  const ou15 = (mb.OU15 ?? {}) as Record<string, unknown>;
  const ou25 = (mb.OU25 ?? {}) as Record<string, unknown>;
  const ou35 = (mb.OU35 ?? {}) as Record<string, unknown>;
  const btts = (mb.BTTS ?? {}) as Record<string, unknown>;

  // V27 predictions
  const v27preds = (v27.predictions ?? {}) as Record<string, unknown>;
  const v27ms = (v27preds.ms ?? {}) as Record<string, number>;

  // Risk breakdown
  const surpriseReasons = (risk.surprise_reasons as string[] | undefined) ?? [];
  const warnings = (risk.warnings as string[] | undefined) ?? [];

  // Top 5 scenarios
  const top5 = (p.scenario_top5 ?? []).slice(0, 5);

  const analysisData = {
    mac: `${home} - ${away} (${league})`,
    ms_olasilik: {
      ev_sahibi_kazanir: ms.probs ? (mb.MS as Record<string, unknown>)?.probs : null,
      v27_ev_sahibi: v27ms.home ? Math.round(v27ms.home * 100) : null,
    },
    xg: { ev_sahibi: sp.xg_home, deplasman: sp.xg_away, toplam: sp.xg_total },
    gol_marketleri: {
      "1_5_ust": (ou15.probs as Record<string, number> | undefined)?.over,
      "2_5_ust": (ou25.probs as Record<string, number> | undefined)?.over,
      "3_5_alt": (ou35.probs as Record<string, number> | undefined)?.under,
      kg_var: (btts.probs as Record<string, number> | undefined)?.yes,
    },
    skor_tahmini: sp.ft,
    en_olasilar: top5.map((s) => `${s.score}: %${Math.round(s.prob * 100)}`),
    risk: { seviye: risk.level, surpriz_skoru: risk.surprise_score, uyarilar: [...surpriseReasons, ...warnings].slice(0, 3) },
    bahis_tavsiyesi: { oynanabilir: ba.playable, karar: ba.decision, neden: ba.reason },
    kadro: { kaynak: dq.lineup_source, kalite: dq.score },
  };

  return `Sen bir futbol bahis analistisin. Aşağıdaki maç analizini okuyup SADECE TÜRKÇE 2-3 cümle yorum yaz. Sayıları tekrar etme, anlam çıkar.

${JSON.stringify(analysisData, null, 2)}

Türkçe yorum:`;
}

export async function generateExpertCommentary(
  prediction: PredictionData,
): Promise<string | null> {
  const prompt = buildPrompt(prediction);
  return generateOllamaText(prompt);
}
