/**
 * Full Sport Guru Audit - 25 Questions
 * Tests Data Sheriff + Grok Integration
 */

const BASE_URL = "http://localhost:3000";

const QUESTIONS = [
  // Team Performance (5)
  { q: "How did the Chiefs do in their last game?", cat: "Team" },
  { q: "What is the Lakers record this season?", cat: "Team" },
  { q: "Are the Bills good against the spread?", cat: "Team" },
  { q: "How are the Celtics performing at home?", cat: "Team" },
  { q: "Eagles recent form - are they covering?", cat: "Team" },
  
  // Player Stats (5)
  { q: "LeBron James scoring stats this season", cat: "Player" },
  { q: "Patrick Mahomes passing yards this year", cat: "Player" },
  { q: "Stephen Curry three point percentage", cat: "Player" },
  { q: "How is Jalen Hurts playing lately?", cat: "Player" },
  { q: "Giannis Antetokounmpo averages", cat: "Player" },
  
  // Matchups (5)
  { q: "Lakers vs Celtics - who has the edge?", cat: "Matchup" },
  { q: "Bills vs Ravens spread prediction", cat: "Matchup" },
  { q: "Chiefs vs Raiders tonight", cat: "Matchup" },
  { q: "Bucks vs Heat matchup analysis", cat: "Matchup" },
  { q: "Cowboys vs Eagles - divisional rivalry", cat: "Matchup" },
  
  // Betting Analysis (5)
  { q: "Warriors moneyline worth it tonight?", cat: "Betting" },
  { q: "Is there value on Nuggets -3.5?", cat: "Betting" },
  { q: "Dolphins spread this week - any edge?", cat: "Betting" },
  { q: "Thunder vs Spurs over/under analysis", cat: "Betting" },
  { q: "Knicks ATS record on the road", cat: "Betting" },
  
  // Complex/Multi-entity (5)
  { q: "Compare LeBron James vs Kevin Durant", cat: "Complex" },
  { q: "Chiefs letdown spot after beating Bills, facing Raiders", cat: "Complex" },
  { q: "Lakers on back-to-back vs Heat", cat: "Complex" },
  { q: "Mahomes vs Josh Allen - who is better?", cat: "Complex" },
  { q: "Celtics vs Sixers with Embiid questionable", cat: "Complex" },
];

interface Result {
  question: string;
  category: string;
  dataSheriff: { confidence: number; coverage: number } | null;
  hasResponse: boolean;
  responseLength: number;
  latencyMs: number;
  error?: string;
}

async function runAudit() {
  console.log("=".repeat(70));
  console.log("   SPORT GURU FULL AUDIT - 25 QUESTIONS");
  console.log("   Data Sheriff + Grok Integration");
  console.log("=".repeat(70) + "\n");
  
  const results: Result[] = [];
  let currentCat = "";
  
  for (let i = 0; i < QUESTIONS.length; i++) {
    const { q, cat } = QUESTIONS[i];
    
    if (cat !== currentCat) {
      console.log("\n" + "─".repeat(70));
      console.log("  " + cat.toUpperCase());
      console.log("─".repeat(70));
      currentCat = cat;
    }
    
    process.stdout.write("[" + (i+1) + "/" + QUESTIONS.length + "] " + q.substring(0, 45).padEnd(45) + " ");
    
    const result: Result = {
      question: q,
      category: cat,
      dataSheriff: null,
      hasResponse: false,
      responseLength: 0,
      latencyMs: 0
    };
    
    try {
      const start = Date.now();
      const response = await fetch(BASE_URL + "/api/chat?internal=1", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: q, userId: "audit", domain: "sports" })
      });
      result.latencyMs = Date.now() - start;
      
      if (!response.ok) {
        result.error = "HTTP " + response.status;
        console.log("ERR");
        results.push(result);
        continue;
      }
      
      const data = await response.json();
      
      if (data.dataSheriff) {
        result.dataSheriff = {
          confidence: data.dataSheriff.confidence,
          coverage: data.dataSheriff.coverage
        };
      }
      
      const content = data.message?.content || data.response || "";
      if (content) {
        result.hasResponse = true;
        result.responseLength = content.length;
      }
      
      const conf = result.dataSheriff ? Math.round(result.dataSheriff.confidence * 100) : 0;
      const status = result.hasResponse ? "OK" : "NO-RESP";
      console.log(status + " " + conf + "% " + (result.latencyMs/1000).toFixed(1) + "s");
      
    } catch (err: any) {
      result.error = err.message;
      console.log("ERR");
    }
    
    results.push(result);
  }
  
  // Summary
  console.log("\n" + "=".repeat(70));
  console.log("   SUMMARY");
  console.log("=".repeat(70));
  
  const successful = results.filter(r => r.hasResponse).length;
  const withDS = results.filter(r => r.dataSheriff).length;
  const avgConf = results.filter(r => r.dataSheriff).reduce((a, r) => a + (r.dataSheriff?.confidence || 0), 0) / withDS;
  const avgCov = results.filter(r => r.dataSheriff).reduce((a, r) => a + (r.dataSheriff?.coverage || 0), 0) / withDS;
  const avgLatency = results.reduce((a, r) => a + r.latencyMs, 0) / results.length;
  
  console.log("\n  Overall:");
  console.log("    Successful:      " + successful + "/" + results.length + " (" + Math.round(successful/results.length*100) + "%)");
  console.log("    Data Sheriff:    " + withDS + "/" + results.length);
  console.log("    Avg Confidence:  " + Math.round(avgConf * 100) + "%");
  console.log("    Avg Coverage:    " + Math.round(avgCov * 100) + "%");
  console.log("    Avg Latency:     " + (avgLatency/1000).toFixed(1) + "s");
  
  // By category
  console.log("\n  By Category:");
  const cats = ["Team", "Player", "Matchup", "Betting", "Complex"];
  for (const c of cats) {
    const catResults = results.filter(r => r.category === c);
    const catSuccess = catResults.filter(r => r.hasResponse).length;
    const catConf = catResults.filter(r => r.dataSheriff).reduce((a, r) => a + (r.dataSheriff?.confidence || 0), 0) / catResults.length;
    console.log("    " + c.padEnd(10) + ": " + catSuccess + "/" + catResults.length + " success, " + Math.round(catConf * 100) + "% conf");
  }
  
  // Errors
  const errors = results.filter(r => r.error);
  if (errors.length > 0) {
    console.log("\n  Errors:");
    for (const e of errors) {
      console.log("    - " + e.question.substring(0, 40) + ": " + e.error);
    }
  }
  
  console.log("\n" + "=".repeat(70));
}

runAudit().catch(console.error);
