/**
 * Corner Scout Service
 *
 * Loads Corner Scout analysis for soccer matches and provides data
 * for injection into Grok prompts for soccer game forecasts.
 *
 * Data source: ~/scripts/corner_scout.py --json output
 * Picks dir: ~/picks/corner_scout_{date}.json
 */

import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { getCurrentEtDateKey } from '../lib/league-windows';

const PICKS_DIR = '/home/administrator/.openclaw/agents/sportsclaw/workspace/picks';
const SCOUT_SCRIPT = '/home/administrator/scripts/corner_scout.py';

export interface CornerScoutMatch {
  home: string;
  away: string;
  league: string;
  kickoff: string;
  projection: number | null;
  market_projection: number | null;
  team_projection: number | null;
  method: string;
  main_line: number | null;
  main_over_odds: number | null;
  main_over_prob: number | null;
  edge: number | null;
  rating: string;
  home_stats: {
    team: string;
    gp: number;
    corners_for: number;
    corners_against: number;
    total: number;
    over_8_5_pct: number | null;
    over_9_5_pct: number | null;
    over_10_5_pct: number | null;
  } | null;
  away_stats: {
    team: string;
    gp: number;
    corners_for: number;
    corners_against: number;
    total: number;
    over_8_5_pct: number | null;
    over_9_5_pct: number | null;
    over_10_5_pct: number | null;
  } | null;
  probabilities: Record<string, number>;
  corner_spread: {
    team: string;
    point: number;
    odds: number;
    book: string;
  } | null;
}

const cornerScoutCache = new Map<string, CornerScoutMatch[]>();

/** Load Corner Scout data for a date. Runs the script if file doesn't exist. */
export function loadCornerScoutData(date?: string): CornerScoutMatch[] {
  const targetDate = date || getCurrentEtDateKey();
  if (cornerScoutCache.has(targetDate)) return cornerScoutCache.get(targetDate)!;
  const filePath = path.join(PICKS_DIR, `corner_scout_${targetDate}.json`);

  // Try loading cached file first
  if (fs.existsSync(filePath)) {
    try {
      const raw = fs.readFileSync(filePath, 'utf-8');
      const data = JSON.parse(raw);
      if (Array.isArray(data) && data.length > 0) {
        console.log(`Corner Scout: Loaded ${data.length} matches for ${targetDate} (cached)`);
        cornerScoutCache.set(targetDate, data);
        return data;
      }
    } catch (err) {
      console.error(`Corner Scout: Failed to parse cached file:`, err);
    }
  }

  // Run the script to generate fresh data
  try {
    console.log(`Corner Scout: Running analysis for ${targetDate}...`);
    const result = execSync(
      `python3 ${SCOUT_SCRIPT} --date ${targetDate} --json`,
      { timeout: 120000, encoding: 'utf-8' }
    );
    const data = JSON.parse(result);

    // Cache the result
    try {
      fs.mkdirSync(path.dirname(filePath), { recursive: true });
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
    } catch (writeErr) {
      // Non-fatal, continue
    }

    console.log(`Corner Scout: Generated ${data.length} matches for ${targetDate}`);
    cornerScoutCache.set(targetDate, data);
    return data;
  } catch (err) {
    console.error(`Corner Scout: Script execution failed:`, err);
    return [];
  }
}

/**
 * Find Corner Scout data for a specific game by matching team names.
 * Uses fuzzy matching (substring, normalized).
 */
export function getCornerScoutForGame(
  homeTeam: string,
  awayTeam: string,
  scoutData?: CornerScoutMatch[],
  date?: string,
): CornerScoutMatch | null {
  const data = scoutData || loadCornerScoutData(date);

  const normalize = (s: string) => s.toLowerCase().replace(/[^a-z0-9\s]/g, '').trim();
  const homeNorm = normalize(homeTeam);
  const awayNorm = normalize(awayTeam);

  for (const match of data) {
    const mHome = normalize(match.home);
    const mAway = normalize(match.away);

    // Exact or substring match
    if (
      (mHome === homeNorm || mHome.includes(homeNorm) || homeNorm.includes(mHome)) &&
      (mAway === awayNorm || mAway.includes(awayNorm) || awayNorm.includes(mAway))
    ) {
      return match;
    }
  }

  // Fallback: try matching just the key word (longest word >= 4 chars)
  const keyWord = (s: string) => {
    const words = normalize(s).split(' ').filter(w => w.length >= 4);
    return words.length > 0 ? words.reduce((a, b) => a.length >= b.length ? a : b) : '';
  };

  const homeKey = keyWord(homeTeam);
  const awayKey = keyWord(awayTeam);

  for (const match of data) {
    const mHomeKey = keyWord(match.home);
    const mAwayKey = keyWord(match.away);

    if (homeKey && awayKey && mHomeKey === homeKey && mAwayKey === awayKey) {
      return match;
    }
  }

  return null;
}

/**
 * Format Corner Scout data for injection into the Grok prompt.
 * Returns a structured text block with corner analysis.
 */
export function formatCornerScoutForPrompt(match: CornerScoutMatch): string {
  const lines: string[] = [
    '--- CORNER SCOUT ANALYSIS ---',
  ];

  // Team stats
  if (match.home_stats) {
    lines.push(`${match.home}: ${match.home_stats.corners_for.toFixed(1)} corners for / ${match.home_stats.corners_against.toFixed(1)} against / ${match.home_stats.total.toFixed(1)} total per game (${match.home_stats.gp} GP)`);
    if (match.home_stats.over_10_5_pct !== null) {
      lines.push(`  Over 10.5 in ${match.home_stats.over_10_5_pct}% of games`);
    }
  }
  if (match.away_stats) {
    lines.push(`${match.away}: ${match.away_stats.corners_for.toFixed(1)} corners for / ${match.away_stats.corners_against.toFixed(1)} against / ${match.away_stats.total.toFixed(1)} total per game (${match.away_stats.gp} GP)`);
    if (match.away_stats.over_10_5_pct !== null) {
      lines.push(`  Over 10.5 in ${match.away_stats.over_10_5_pct}% of games`);
    }
  }

  // Projection
  if (match.projection !== null) {
    lines.push(`Corner Projection: ${match.projection.toFixed(1)} (method: ${match.method})`);
    if (match.market_projection !== null && match.team_projection !== null) {
      lines.push(`  Market-derived: ${match.market_projection.toFixed(1)} | Team model: ${match.team_projection.toFixed(1)}`);
    }
  }

  // Market line + edge
  if (match.main_line !== null) {
    lines.push(`Corner Line: ${match.main_line} (Over: ${match.main_over_odds}, implied ${((match.main_over_prob || 0) * 100).toFixed(0)}%)`);
    if (match.edge !== null) {
      const dir = match.edge > 0 ? 'OVER' : 'UNDER';
      lines.push(`Edge: ${dir} by ${Math.abs(match.edge).toFixed(1)} corners`);
    }
  }

  // Probabilities
  if (Object.keys(match.probabilities).length > 0) {
    const probs = Object.entries(match.probabilities)
      .map(([k, v]) => `O${k}: ${(v * 100).toFixed(0)}%`)
      .join(' | ');
    lines.push(`Probabilities: ${probs}`);
  }

  lines.push(`Rating: ${match.rating}`);
  lines.push('--- END CORNER SCOUT ---');

  return lines.join('\n');
}

/**
 * Check if a league is a soccer league (for determining when to load Corner Scout).
 */
export function isSoccerLeague(league: string): boolean {
  const soccerLeagues = [
    'epl', 'la_liga', 'serie_a', 'bundesliga', 'ligue_1',
    'eredivisie', 'mls', 'primeira_liga', 'super_lig',
    'premier league', 'la liga', 'serie a', 'ligue 1',
    'soccer_epl', 'soccer_spain_la_liga', 'soccer_germany_bundesliga',
    'soccer_italy_serie_a', 'soccer_france_ligue_one',
    'soccer_usa_mls', 'soccer_netherlands_eredivisie',
  ];
  return soccerLeagues.includes(league.toLowerCase());
}
