/**
 * CLV (Closing Line Value) tracker.
 *
 * For each resolved grade, compare the line at which we graded (open) to
 * the line at game start (close). Positive CLV means the line moved
 * toward us — a leading indicator of long-term profitability that's
 * independent of whether the prop actually hit.
 */

const { americanToImplied } = require('./LineShoppingEngine');

/**
 * @param {{graded_line:number, graded_odds:number, close_line:number, close_odds:number, direction:'over'|'under'}} entry
 */
function clvFor(entry) {
  if (!entry) return null;
  const dir = entry.direction;
  const gI = americanToImplied(entry.graded_odds);
  const cI = americanToImplied(entry.close_odds);
  if (gI == null || cI == null) return null;
  // Over: line went DOWN = good for us (book thinks fewer); odds went up
  // (less juice). We compute edge as (graded_implied - close_implied) for
  // Over and the negation for Under so a positive value always means CLV+.
  const oddsClv = dir === 'over' ? gI - cI : cI - gI;
  const lineDelta = entry.close_line - entry.graded_line;
  const lineClv = dir === 'over' ? -lineDelta : lineDelta;
  return {
    odds_clv: oddsClv,
    line_clv: lineClv,
    positive: oddsClv > 0 || lineClv > 0,
  };
}

function summarize(entries) {
  const items = (entries || []).map((e) => ({ ...e, clv: clvFor(e) })).filter((e) => e.clv);
  if (!items.length) return { count: 0, positive_rate: null, avg_odds_clv: null, avg_line_clv: null };
  const positive = items.filter((i) => i.clv.positive).length;
  const avgOdds = items.reduce((s, i) => s + i.clv.odds_clv, 0) / items.length;
  const avgLine = items.reduce((s, i) => s + i.clv.line_clv, 0) / items.length;
  return {
    count: items.length,
    positive_rate: positive / items.length,
    avg_odds_clv: avgOdds,
    avg_line_clv: avgLine,
  };
}

module.exports = { clvFor, summarize };
