import type { GameData, OddsRow, InjuryData, PropData, LineMovementData, SharpMoveData, CLVData } from './data-queries';

// Helper: format American odds for display
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';
}

// ── GAME PREVIEW PROMPT ──────────────────────────────────────────
export function gamePreviewPrompt(
  game: GameData,
  odds: OddsRow[],
  injuries: InjuryData[],
  league: string
): string {
  const awayInjuries = injuries.filter(i => i.team === game.awayTeam);
  const homeInjuries = injuries.filter(i => i.team === game.homeTeam);

  const oddsTable = odds.length > 0
    ? odds.filter(o => o.market === 'h2h' || o.market === 'spreads' || o.market === 'totals')
      .slice(0, 15)
      .map(o => `  ${o.bookmaker}: market=${o.market}, line=${o.lineValue}, home=${fmtOdds(o.homeOdds)}, away=${fmtOdds(o.awayOdds)}, over=${fmtOdds(o.overOdds)}, under=${fmtOdds(o.underOdds)}`)
      .join('\n')
    : 'No sportsbook odds available yet.';

  const injurySection = (team: string, inj: InjuryData[]) =>
    inj.length > 0
      ? inj.map(i => `  ${i.playerName} (${i.position || '?'}) - ${i.status}: ${i.injuryType || 'undisclosed'}${i.expectedReturn ? ` (return: ${i.expectedReturn})` : ''}`).join('\n')
      : '  No significant injuries reported.';

  return `You are an expert sports analyst writing for SportsClaw, a sports betting data platform.

Write a GAME PREVIEW article for: ${game.awayTeam} at ${game.homeTeam}
League: ${league.toUpperCase()}
Game Date: ${fmtDate(game.gameDate)}
Game Time: ${fmtTime(game.gameDate)}

CURRENT ODDS:
  Consensus Spread: ${game.homeTeam} ${fmtLine(game.spreadHome)}
  Consensus Total: O/U ${game.total || 'N/A'}
  Moneyline: ${game.homeTeam} ${fmtOdds(game.moneylineHome)} / ${game.awayTeam} ${fmtOdds(game.moneylineAway)}

SPORTSBOOK ODDS (by bookmaker):
${oddsTable}

INJURIES - ${game.awayTeam}:
${injurySection(game.awayTeam, awayInjuries)}

INJURIES - ${game.homeTeam}:
${injurySection(game.homeTeam, homeInjuries)}

INSTRUCTIONS:
Write a complete, SEO-optimized game preview following this EXACT structure. Return ONLY valid JSON.

{
  "title": "[keyword-rich title, max 70 chars, format: 'Team vs Team Odds, Picks & Prediction — Date']",
  "meta_description": "[compelling meta desc, 150-160 chars, include key odds numbers]",
  "h1": "[same or slightly different from title, include team names and 'odds']",
  "excerpt": "[40-60 word direct answer stating who the pick is and why, as if answering 'Who will win Team vs Team tonight?' — this targets Google featured snippets]",
  "quick_facts": [
    {"label": "Game", "value": "${game.awayTeam} at ${game.homeTeam}"},
    {"label": "Date", "value": "[formatted date and time ET]"},
    {"label": "Spread", "value": "[team and spread]"},
    {"label": "Total", "value": "O/U [number]"},
    {"label": "Moneyline", "value": "[home odds / away odds]"},
    {"label": "Home", "value": "${game.homeTeam}"},
    {"label": "Away", "value": "${game.awayTeam}"}
  ],
  "content": "[full HTML article content — 1500+ chars. Use <h2>, <h3>, <p>, <strong>, <ul>, <li> tags. Cover: matchup analysis, key injuries impact, odds analysis, best bet recommendation. End with 'Updated [date]. Data from 40+ sportsbooks tracked in real-time.' and link to Telegram bot.]",
  "faq_schema": [
    {"question": "What are the odds for [Team] vs [Team]?", "answer": "[40-60 word answer with specific numbers]"},
    {"question": "Who is favored in [Team] vs [Team]?", "answer": "[clear answer with spread/moneyline]"},
    {"question": "What is the over/under for [Team] vs [Team]?", "answer": "[answer with total and analysis]"},
    {"question": "[injury-related question if relevant]", "answer": "[answer]"},
    {"question": "[best bet or prediction question]", "answer": "[answer with pick]"}
  ],
  "data_tables": {
    "odds": [
      {"sportsbook": "[name]", "spread": "[value]", "total": "[value]", "moneyline": "[value]"}
    ]
  }
}

CRITICAL RULES:
- The excerpt MUST be a standalone answer (40-60 words) that directly answers the search query
- FAQ answers MUST be 40-60 words each
- Content must be 1500+ characters of HTML
- Include specific odds numbers throughout
- Be confident in analysis but include disclaimer language
- Do NOT include any markdown — only valid HTML in the content field
- Return ONLY the JSON object, no surrounding text`;
}

// ── PROPS ANALYSIS PROMPT ──────────────────────────────────────
export function propsAnalysisPrompt(
  league: string,
  props: PropData[],
  date: Date
): string {
  const propList = props.slice(0, 30).map(p =>
    `  ${p.playerName || p.playerExternalId}: ${p.propType} ${p.lineValue} (${fmtOdds(p.oddsAmerican)}) [${p.vendor || 'unknown'}]`
  ).join('\n');

  return `You are an expert sports analyst writing for SportsClaw.

Write a PLAYER PROPS ANALYSIS for ${league.toUpperCase()} on ${fmtDate(date.toISOString())}.

AVAILABLE PROPS DATA:
${propList}

INSTRUCTIONS:
Write an SEO-optimized props analysis article. Return ONLY valid JSON.

{
  "title": "Best ${league.toUpperCase()} Player Props Today — ${fmtDate(date.toISOString()).split(',')[0]} Picks",
  "meta_description": "[150-160 chars about today's best ${league.toUpperCase()} player props with specific player names]",
  "h1": "Best ${league.toUpperCase()} Player Props Today — Top Picks for ${fmtDate(date.toISOString())}",
  "excerpt": "[40-60 word summary of top 2-3 prop picks with reasoning — targets 'best ${league} props today' snippet]",
  "quick_facts": [
    {"label": "Sport", "value": "${league.toUpperCase()}"},
    {"label": "Date", "value": "${fmtDate(date.toISOString())}"},
    {"label": "Props Analyzed", "value": "[number]"},
    {"label": "Top Pick", "value": "[player name + prop]"}
  ],
  "content": "[1500+ chars HTML. For each top prop pick (3-5 picks), use <h3> for player name, discuss the prop type, line, recent performance, and whether over/under is the play. Use <strong> for key numbers. Include <ul> lists for stats.]",
  "faq_schema": [
    {"question": "What are the best ${league.toUpperCase()} player props today?", "answer": "[40-60 words listing top picks]"},
    {"question": "What is [top player]'s prop line today?", "answer": "[specific answer]"},
    {"question": "Should I take the over or under on [player prop]?", "answer": "[analysis]"}
  ],
  "data_tables": {
    "props": [
      {"player": "[name]", "prop": "[type]", "line": "[value]", "over": "[odds]", "under": "[odds]"}
    ]
  }
}

CRITICAL: Return ONLY valid JSON. No markdown, only HTML in content. Excerpt must be 40-60 words.`;
}

// ── LINE MOVEMENT PROMPT ──────────────────────────────────────
export function lineMovementPrompt(
  league: string,
  movements: LineMovementData[],
  sharpMoves: SharpMoveData[]
): string {
  const moveList = movements.slice(0, 15).map(m =>
    `  ${m.homeTeam} vs ${m.awayTeam}: ${m.marketType} moved ${fmtLine(m.openLine)} → ${fmtLine(m.currentLine)} (${m.movementDirection || '?'})${m.steamMove ? ' [STEAM]' : ''}${m.reverseLineMove ? ' [RLM]' : ''} sharp=${m.sharpAction || 'none'}`
  ).join('\n');

  const sharpList = sharpMoves.slice(0, 10).map(s =>
    `  ${s.homeTeam} vs ${s.awayTeam}: ${s.market} ${fmtLine(s.lineFrom)} → ${fmtLine(s.lineTo)} (${s.moveType || '?'})${s.isSteamMove ? ' STEAM' : ''}${s.isReverseLine ? ' RLM' : ''}`
  ).join('\n');

  const today = new Date().toISOString();

  return `You are an expert sports analyst specializing in line movement analysis for SportsClaw.

Write a LINE MOVEMENT ALERT for ${league.toUpperCase()}.

LINE MOVEMENTS (biggest moves):
${moveList || 'No significant movements detected.'}

SHARP MONEY MOVES:
${sharpList || 'No sharp moves detected.'}

INSTRUCTIONS:
Write an SEO-optimized line movement analysis. Return ONLY valid JSON.

{
  "title": "${league.toUpperCase()} Line Movement & Sharp Money Alert — ${fmtDate(today).split(',')[0]}",
  "meta_description": "[150-160 chars about biggest ${league} line moves, steam moves, and sharp action today]",
  "h1": "${league.toUpperCase()} Sharp Money & Line Movement Report — ${fmtDate(today)}",
  "excerpt": "[40-60 word summary of the biggest line moves and what sharp bettors are targeting — targets 'sharp money ${league} today' snippet]",
  "quick_facts": [
    {"label": "Sport", "value": "${league.toUpperCase()}"},
    {"label": "Moves Tracked", "value": "[number]"},
    {"label": "Steam Moves", "value": "[number]"},
    {"label": "Reverse Line Moves", "value": "[number]"}
  ],
  "content": "[1500+ chars HTML. Cover: biggest line movements with analysis, steam moves explanation, reverse line moves, sharp vs public action. Use <h2>/<h3> headings. Include specific numbers.]",
  "faq_schema": [
    {"question": "Where is the sharp money going in ${league.toUpperCase()} today?", "answer": "[40-60 words]"},
    {"question": "What is a steam move in sports betting?", "answer": "[educational answer]"},
    {"question": "Which ${league.toUpperCase()} games have the biggest line moves today?", "answer": "[specific answer]"}
  ],
  "data_tables": {
    "odds": [
      {"sportsbook": "Line Movement", "spread": "[open → current]", "total": "[direction]", "moneyline": "[sharp indicator]"}
    ]
  }
}

CRITICAL: Return ONLY valid JSON. No markdown. Excerpt 40-60 words.`;
}

// ── WEEKLY RECAP PROMPT ────────────────────────────────────────
export function weeklyRecapPrompt(
  league: string,
  games: GameData[],
  clvData: CLVData[],
  weekLabel: string
): string {
  const gameResults = games.slice(0, 20).map(g =>
    `  ${g.awayTeam} ${g.awayScore || '?'} @ ${g.homeTeam} ${g.homeScore || '?'} (spread: ${fmtLine(g.spreadHome)}, total: ${g.total || '?'})`
  ).join('\n');

  const clvResults = clvData.slice(0, 10).map(c =>
    `  ${c.homeTeam} vs ${c.awayTeam}: ${c.market} ${c.side} — CLV: ${c.clvPercent?.toFixed(1)}%, beat close: ${c.beatClose ? 'YES' : 'NO'}, result: ${c.actualResult || '?'}, profit: ${c.profit?.toFixed(2) || '?'}`
  ).join('\n');

  return `You are an expert sports analyst writing a weekly recap for SportsClaw.

Write a WEEKLY RECAP for ${league.toUpperCase()} — ${weekLabel}.

GAME RESULTS:
${gameResults || 'No completed games.'}

CLV ANALYSIS (closing line value):
${clvResults || 'No CLV data available.'}

Total games: ${games.length}

INSTRUCTIONS:
Write a comprehensive weekly recap. Return ONLY valid JSON.

{
  "title": "${league.toUpperCase()} Betting Recap ${weekLabel} — Results, ATS Records & CLV Analysis",
  "meta_description": "[150-160 chars summarizing the week's betting results and key takeaways]",
  "h1": "${league.toUpperCase()} Betting Recap ${weekLabel}",
  "excerpt": "[40-60 word summary of key results and ATS performance — targets '${league} betting recap' snippet]",
  "quick_facts": [
    {"label": "Sport", "value": "${league.toUpperCase()}"},
    {"label": "Week", "value": "${weekLabel}"},
    {"label": "Games", "value": "${games.length}"},
    {"label": "Key Stat", "value": "[notable ATS or CLV stat]"}
  ],
  "content": "[1500+ chars HTML. Cover: overview of the week, notable results, ATS trends, CLV performance, biggest surprises, look-ahead. Use tables, lists, and specific numbers.]",
  "faq_schema": [
    {"question": "How did ${league.toUpperCase()} teams perform against the spread this week?", "answer": "[40-60 words]"},
    {"question": "What were the biggest ${league.toUpperCase()} betting surprises this week?", "answer": "[40-60 words]"},
    {"question": "What is closing line value (CLV) in sports betting?", "answer": "[educational answer]"}
  ],
  "data_tables": {}
}

CRITICAL: Return ONLY valid JSON.`;
}

// ── EDUCATIONAL GUIDE PROMPT ─────────────────────────────────
export function educationalGuidePrompt(
  topic: string,
  ragContent: string
): string {
  return `You are an expert sports betting educator writing for SportsClaw.

Write an EDUCATIONAL GUIDE about: "${topic}"

REFERENCE CONTENT (from our knowledge base):
${ragContent || 'No reference content available — use your expertise.'}

INSTRUCTIONS:
Write a comprehensive, beginner-friendly guide. Target the featured snippet for "${topic}" queries.
Return ONLY valid JSON.

{
  "title": "[Title targeting the query '${topic}', max 70 chars]",
  "meta_description": "[150-160 chars answering '${topic}' directly]",
  "h1": "[Clear h1 including the key phrase]",
  "excerpt": "[40-60 word direct answer to '${topic}' — this is the featured snippet target. Answer as if explaining to someone who just Googled this.]",
  "quick_facts": [
    {"label": "Topic", "value": "[short topic]"},
    {"label": "Difficulty", "value": "[Beginner/Intermediate/Advanced]"},
    {"label": "Read Time", "value": "[X min]"}
  ],
  "content": "[2000+ chars HTML. Use <h2> and <h3> for sections. Include: definition, how it works, examples with numbers, common mistakes, pro tips. Be thorough but clear. Use <strong>, <ul>, <li>, <p> tags. Include real betting examples.]",
  "faq_schema": [
    {"question": "${topic}?", "answer": "[direct 40-60 word answer]"},
    {"question": "[related question 1]", "answer": "[answer]"},
    {"question": "[related question 2]", "answer": "[answer]"},
    {"question": "[related question 3]", "answer": "[answer]"},
    {"question": "[related question 4]", "answer": "[answer]"}
  ],
  "data_tables": {}
}

CRITICAL: Return ONLY valid JSON. Make the excerpt a standalone answer. Content must be educational and authoritative.`;
}

// ── GUIDE TOPICS ─────────────────────────────────────────────
export const GUIDE_TOPICS = [
  'how to read odds',
  'what is a spread in sports betting',
  'what is a moneyline bet',
  'what are player props in sports betting',
  'how does the over under work',
  'what is a parlay bet',
  'what is closing line value CLV',
  'how to find sharp money moves',
  'what is a reverse line movement',
  'what is a steam move in sports betting',
  'how to bet on NBA games',
  'how to bet on NFL games',
  'what is juice or vig in sports betting',
  'what does ATS mean in sports betting',
  'how to read player prop lines',
  'what is a teaser bet',
  'how sportsbooks set their lines',
  'bankroll management for sports betting',
  'live betting strategy explained',
  'how to use odds comparison tools',
];
