/**
 * DIGIMON v1.4 DVP Miss Pattern Loader
 *
 * Reads today's DIGIMON pick files and exposes verdicts by team abbreviation.
 * Mirrors the piff.ts pattern for Grok prompt injection.
 */

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

const PICKS_DIR = '/home/administrator/.openclaw/agents/sportsclaw/workspace/picks';

export interface DigimonPick {
  player: string;
  team: string;       // abbreviation e.g. "ATL"
  prop: string;       // "PTS" or "REB"
  line: number;       // book line
  digiLine: number;   // book - drop
  odds: number;       // American odds
  dvp: string;        // e.g. "OPP G Rk 5 easy"
  dvpRank: number;
  dvpTier: string;    // "easy", "avg", "elite"
  missRate: number;   // 0-1 fraction
  misses: string;     // "2/15 easy" display string
  verdict: string;    // "LOCK", "PLAY", "LEAN", "SKIP"
  reason?: string;
}

interface DigimonFile {
  date: string;
  games: Array<{
    game: string;
    spread?: string;
    picks: DigimonPick[];
  }>;
  total_picks?: number;
}

/** Load and parse a DIGIMON JSON file */
function loadDigimonFile(filePath: string): DigimonPick[] {
  try {
    if (!fs.existsSync(filePath)) return [];
    const raw = fs.readFileSync(filePath, 'utf-8');
    const data: DigimonFile = JSON.parse(raw);
    const picks: DigimonPick[] = [];
    for (const game of (data.games || [])) {
      for (const pick of (game.picks || [])) {
        picks.push(pick);
      }
    }
    return picks;
  } catch (err) {
    console.error(`Failed to load DIGIMON file ${filePath}:`, err);
    return [];
  }
}

// Cache per process
const digimonCache = new Map<string, Record<string, DigimonPick[]>>();

/**
 * Load all DIGIMON picks for an ET date, indexed by uppercase team abbreviation.
 */
export function loadDigimonPicksForDate(date: string = getCurrentEtDateKey()): Record<string, DigimonPick[]> {
  if (digimonCache.has(date)) return digimonCache.get(date)!;

  const map: Record<string, DigimonPick[]> = {};

  // Try multiple file name patterns
  const patterns = [
    `digimon_${date}.json`,
    `digimon_v14_${date}.json`,
    `dvp_picks_${date}.json`,
    `defense_${date}.json`,
  ];

  let allPicks: DigimonPick[] = [];
  for (const pattern of patterns) {
    const picks = loadDigimonFile(path.join(PICKS_DIR, pattern));
    if (picks.length > 0) {
      allPicks = picks;
      break;
    }
  }

  for (const pick of allPicks) {
    const key = pick.team.toUpperCase();
    if (!map[key]) map[key] = [];
    map[key].push(pick);
  }

  console.log(`DIGIMON v1.4: Loaded ${allPicks.length} picks across ${Object.keys(map).length} teams for ${date}`);
  digimonCache.set(date, map);
  return map;
}

export function loadTodaysDigimonPicks(): Record<string, DigimonPick[]> {
  return loadDigimonPicksForDate(getCurrentEtDateKey());
}

/**
 * Get DIGIMON picks for a specific game by matching team abbreviations.
 */
export function getDigimonForGame(
  homeShort: string,
  awayShort: string,
  digiMap?: Record<string, DigimonPick[]>
): DigimonPick[] {
  const map = digiMap || loadTodaysDigimonPicks();
  const homeKey = homeShort.toUpperCase();
  const awayKey = awayShort.toUpperCase();
  return [...(map[homeKey] || []), ...(map[awayKey] || [])];
}

/**
 * Format DIGIMON picks into a prompt section for Grok.
 */
export function formatDigimonForPrompt(picks: DigimonPick[]): string {
  if (picks.length === 0) return '';

  const locks = picks.filter(p => p.verdict === 'LOCK');
  const plays = picks.filter(p => p.verdict === 'PLAY');
  const leans = picks.filter(p => p.verdict === 'LEAN');

  const formatPick = (p: DigimonPick): string => {
    const missRatePct = Math.round(p.missRate * 100);
    return `- ${p.player} O${p.line} ${p.prop}: ${p.misses} miss rate vs ${p.dvpTier} defense (${p.verdict})`;
  };

  const lines: string[] = [];
  if (locks.length > 0) {
    lines.push(`LOCKs (0-15% miss rate): ${locks.map(formatPick).join('\n')}`);
  }
  if (plays.length > 0) {
    lines.push(`PLAYs (16-25% miss rate): ${plays.map(formatPick).join('\n')}`);
  }
  if (leans.length > 0) {
    lines.push(`LEANs (26-35% miss rate): ${leans.map(formatPick).join('\n')}`);
  }

  return `\nRAIN MAN PATTERN LOCK (83.3% hit rate, NBA only):\n${lines.join('\n')}\nWeight LOCK verdicts heavily in your prop_highlights. These have historically hit at 90%+ rate.`;
}
