/**
 * RIE Signal: Corner Scout (Soccer Corners)
 *
 * Wraps existing corner-scout.ts. Soccer leagues only.
 * Converts corner projection edge into a 0-1 confidence signal.
 */

import { Signal, SignalResult, MatchupContext } from '../types';
import { getCornerScoutForGame, loadCornerScoutData, isSoccerLeague, CornerScoutMatch } from '../../corner-scout';
import { getCurrentEtDateKey, getEtDateKey } from '../../../lib/league-windows';

function clamp(val: number, min: number, max: number): number {
  return Math.max(min, Math.min(max, val));
}

const SOCCER_LEAGUES = ['epl', 'la_liga', 'bundesliga', 'serie_a', 'ligue_1', 'champions_league'];

export const cornerScoutSignal: Signal = {
  id: 'corner_scout',
  name: 'Corner Scout Projections',
  supportedLeagues: SOCCER_LEAGUES,

  async collect(ctx: MatchupContext): Promise<SignalResult> {
    const start = Date.now();
    try {
      const targetDate = getEtDateKey(ctx.startsAt || '') || getCurrentEtDateKey();
      const scoutData = await loadCornerScoutData(targetDate);
      const match = getCornerScoutForGame(ctx.homeTeam, ctx.awayTeam, scoutData);

      if (!match || match.projection === null) {
        return {
          signalId: 'corner_scout', score: 0.5, weight: 0, available: false,
          rawData: { reason: 'no corner scout data for matchup' },
          metadata: { latencyMs: Date.now() - start, source: 'file', freshness: '' },
        };
      }

      const edge = match.edge ?? 0;
      const absEdge = Math.abs(edge);
      // Each corner of edge ≈ 0.13 confidence boost from neutral
      let score = clamp(0.5 + absEdge * 0.13, 0.5, 0.95);

      if (match.rating === 'STRONG BET') {
        score = clamp(score + 0.05, 0.5, 0.98);
      } else if (match.rating === 'LEAN') {
        score = clamp(score + 0.02, 0.5, 0.95);
      }

      return {
        signalId: 'corner_scout',
        score,
        weight: 0,
        available: true,
        rawData: {
          projection: match.projection,
          edge: match.edge,
          rating: match.rating,
          homeStats: match.home_stats || null,
          awayStats: match.away_stats || null,
          cornerSpread: match.corner_spread || null,
        },
        metadata: {
          latencyMs: Date.now() - start,
          source: 'file',
          freshness: targetDate,
        },
      };
    } catch (err) {
      return {
        signalId: 'corner_scout', score: 0.5, weight: 0, available: false,
        rawData: { error: String(err) },
        metadata: { latencyMs: Date.now() - start, source: 'file', freshness: '' },
      };
    }
  },
};
