/**
 * Expected Value calculator.
 *
 * Inputs: book odds + VYNDR's modeled probability (derived from grade tier).
 * Output: edge % and a friendly "+EV: 8.2%" string for the grade card.
 */

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

// Calibrated probabilities per grade tier — these track the published Ledger.
// Refresh from the grade_history table on a schedule.
const GRADE_PROBABILITY = Object.freeze({
  'A+': 0.74,
  'A':  0.65,
  'A-': 0.62,
  'B+': 0.58,
  'B':  0.55,
  'B-': 0.53,
  'C+': 0.50,
  'C':  0.48,
  'C-': 0.46,
  'D':  0.40,
  'F':  0.35,
});

function probabilityForGrade(grade) {
  if (!grade) return null;
  return GRADE_PROBABILITY[grade] ?? GRADE_PROBABILITY[grade[0]] ?? null;
}

/**
 * @param {{grade:string, odds:number}} input
 * @returns {{ev_pct:number, edge_pct:number, label:string}|null}
 */
function calculate({ grade, odds } = {}) {
  const p = probabilityForGrade(grade);
  const implied = americanToImplied(odds);
  if (p == null || implied == null) return null;
  const edge = p - implied;
  const edgePct = edge / implied;
  const sign = edge >= 0 ? '+' : '−';
  return {
    modeled_probability: p,
    implied_probability: implied,
    edge,
    edge_pct: edgePct,
    label: `${sign}EV: ${(Math.abs(edgePct) * 100).toFixed(1)}%`,
  };
}

module.exports = { calculate, probabilityForGrade, GRADE_PROBABILITY };
