/**
 * V2 Prompts — Data-rich, AEO-optimized prompts for SEO content.
 * 
 * Key principles:
 * 1. Feed the LLM REAL DATA, not generic context
 * 2. Pre-compute the analysis — LLM just writes the narrative
 * 3. Structure for AEO (Answer Engine Optimization) — direct answers for AI search
 * 4. Every article should have unique data that no competitor has
 */
import type { EnrichedGameData } from './data-enrichment';

function fmtOdds(odds: number | null): string {
  if (odds == null) return '-';
  return odds > 0 ? `+${odds}` : `${odds}`;
}

function fmtLine(line: number | null): string {
  if (line == null) return '-';
  return line > 0 ? `+${line}` : `${line}`;
}

function fmtDate(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
}

function fmtTime(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', timeZone: 'America/New_York' }) + ' ET';
}

// ── ENRICHED GAME PREVIEW PROMPT ─────────────────────────────
export function enrichedGamePreviewPrompt(data: EnrichedGameData): string {
  const home = data.homeTeamFull;
  const away = data.awayTeamFull;
  const date = fmtDate(data.gameDate);
  const time = fmtTime(data.gameDate);

  // Build rich data sections
  const formSection = `
HOME TEAM FORM (${home}):
  Record (L10): ${data.homeForm.record}
  Scoring: ${data.homeForm.avgPts} PPG / ${data.homeForm.avgPtsAllowed} allowed
  Streak: ${data.homeForm.streak}
${data.homeKeyPlayers.length > 0 ? `  Key Players:\n${data.homeKeyPlayers.map(p => `    ${p.name}: ${p.avg} ${p.stat}/game (high: ${p.value})`).join('\n')}` : ''}

AWAY TEAM FORM (${away}):
  Record (L10): ${data.awayForm.record}
  Scoring: ${data.awayForm.avgPts} PPG / ${data.awayForm.avgPtsAllowed} allowed
  Streak: ${data.awayForm.streak}
${data.awayKeyPlayers.length > 0 ? `  Key Players:\n${data.awayKeyPlayers.map(p => `    ${p.name}: ${p.avg} ${p.stat}/game (high: ${p.value})`).join('\n')}` : ''}`;

  const h2hSection = data.h2h.games > 0
    ? `\nHEAD-TO-HEAD (last ${data.h2h.games} meetings):\n${data.h2h.results.map(r => `  ${r}`).join('\n')}`
    : '';

  const propsSection = data.topProps.length > 0
    ? `\nPLAYER PROPS AVAILABLE:\n${data.topProps.slice(0, 8).map(p => `  ${p.player}: ${p.prop} ${p.line} (Over ${fmtOdds(p.overOdds)})`).join('\n')}`
    : '';

  const dvpSection = data.dvpEdges.length > 0
    ? `\nDEFENSE VS POSITION EDGES:\n${data.dvpEdges.map(d => `  ${d.team} allows ${d.stat} rank #${d.rank} (${d.avgAllowed}/game to ${d.position}s)`).join('\n')}`
    : '';

  const injurySection = data.injuries.length > 0
    ? `\nINJURIES:\n${data.injuries.map(i => `  ${i.team}: ${i.player} (${i.position}) — ${i.status}`).join('\n')}`
    : '\nINJURIES: No significant injuries reported for either team.';

  const lineSection = data.lineMovement.length > 0
    ? `\nLINE MOVEMENT:\n${data.lineMovement.map(l => `  ${l.market}: ${l.open} → ${l.current} (${l.direction})`).join('\n')}`
    : '';

  const modelSection = data.modelPick
    ? `\nSPORTSCLAW MODEL PICK:\n  Pick: ${data.modelPick.pick}\n  Confidence: ${data.modelPick.confidence}\n  Edge: +${data.modelPick.edge}%\n  Reasoning: ${data.modelPick.reasoning}`
    : '';

  return `You are an expert sports analyst writing for SportsClaw. You have access to REAL-TIME DATA from our analytics platform.

Write a data-rich GAME PREVIEW for: ${away} at ${home}
League: ${data.league.toUpperCase()}
Date: ${date} | Time: ${time}

CONSENSUS ODDS:
  Spread: ${home} ${fmtLine(data.consensus.spread)}
  Total: O/U ${data.consensus.total || 'TBD'}
  Moneyline: ${home} ${fmtOdds(data.consensus.homeML)} / ${away} ${fmtOdds(data.consensus.awayML)}
${formSection}
${h2hSection}
${propsSection}
${dvpSection}
${injurySection}
${lineSection}
${modelSection}

INSTRUCTIONS — Write a UNIQUE, DATA-DRIVEN article. Return ONLY valid JSON.

KEY REQUIREMENTS:
1. EXCERPT (40-60 words): Write a DIRECT ANSWER to "Who will win ${away} vs ${home}?" — state the pick, the score prediction, and the key reason. This targets Google Featured Snippets AND AI search (ChatGPT, Perplexity, Gemini).
2. CONTENT: Must include SPECIFIC NUMBERS from the data above. Reference actual player stats, form records, and odds. Do NOT make up stats.
3. Include a "By The Numbers" section with a data comparison table.
4. Include a "Best Bets" section with 2-3 specific picks (spread, total, prop if available).
5. Use HTML formatting: <h2>, <h3>, <p>, <strong>, <ul>, <li>, <table>, <tr>, <td>.
6. End with: "Updated ${date}. All odds and stats powered by SportsClaw — real-time data from 40+ sportsbooks. <a href='https://t.me/sportsclaw_guru_bot'>Get picks on Telegram →</a>"

{
  "title": "${away} at ${home} Odds, Picks & Prediction — ${date.split(',')[0]} ${date.split(' ').pop()}",
  "meta_description": "[155 chars max. Include: team names, spread, total, and your pick. Example: '${away} at ${home}: ${home} ${fmtLine(data.consensus.spread)} spread, O/U ${data.consensus.total}. Our model picks [team]. Expert analysis inside.']",
  "h1": "${away} at ${home} Odds, Picks & Prediction",
  "excerpt": "[CRITICAL: 40-60 word DIRECT ANSWER to 'Who will win?' — state winner, predicted score, and why. This is the #1 most important field for AEO.]",
  "quick_facts": [
    {"label": "Matchup", "value": "${away} at ${home}"},
    {"label": "Date", "value": "${date}, ${time}"},
    {"label": "Spread", "value": "${home} ${fmtLine(data.consensus.spread)}"},
    {"label": "Total", "value": "O/U ${data.consensus.total || 'TBD'}"},
    {"label": "Moneyline", "value": "${home} ${fmtOdds(data.consensus.homeML)} / ${away} ${fmtOdds(data.consensus.awayML)}"},
    {"label": "Best Bet", "value": "[your top pick in 5 words]"},
    {"label": "Prediction", "value": "[predicted score]"}
  ],
  "content": "[2000+ chars HTML. Sections: Matchup Preview (use team form data), By The Numbers (comparison table), Key Injuries, Odds Analysis, Player Props to Watch, Best Bets (2-3 picks), Prediction. Use REAL DATA from above.]",
  "faq_schema": [
    {"question": "What are the ${away} vs ${home} odds today?", "answer": "[40-60 words with specific spread, total, moneyline numbers]"},
    {"question": "Who is favored in ${away} vs ${home}?", "answer": "[direct answer with spread and why]"},
    {"question": "What is the over/under for ${away} vs ${home}?", "answer": "[total number and analysis of scoring trends]"},
    {"question": "What are the best bets for ${away} vs ${home}?", "answer": "[your top 2 picks with reasoning]"},
    {"question": "${data.topProps.length > 0 ? `What are the best player props for ${away} vs ${home}?` : `What is the predicted score for ${away} vs ${home}?`}", "answer": "[specific answer using data]"}
  ],
  "data_tables": {
    "team_comparison": [
      {"stat": "Record (L10)", "home": "${data.homeForm.record}", "away": "${data.awayForm.record}"},
      {"stat": "PPG", "home": "${data.homeForm.avgPts}", "away": "${data.awayForm.avgPts}"},
      {"stat": "Opp PPG", "home": "${data.homeForm.avgPtsAllowed}", "away": "${data.awayForm.avgPtsAllowed}"},
      {"stat": "Streak", "home": "${data.homeForm.streak}", "away": "${data.awayForm.streak}"}
    ],
    "odds": [
      {"market": "Spread", "line": "${fmtLine(data.consensus.spread)}", "home": "${fmtOdds(data.consensus.homeML)}", "away": "${fmtOdds(data.consensus.awayML)}"},
      {"market": "Total", "line": "O/U ${data.consensus.total || 'TBD'}", "home": "-", "away": "-"},
      {"market": "Moneyline", "line": "-", "home": "${fmtOdds(data.consensus.homeML)}", "away": "${fmtOdds(data.consensus.awayML)}"}
    ]
  }
}

CRITICAL: Return ONLY the JSON object. Use REAL numbers from the data. Do NOT invent statistics.`;
}
