/* ============================================================
   pricedLines (Session 79) — the REAL priced lines from the current snapshot,
   indexed for the scanner to surface. Plain CommonJS so it's unit-testable and
   importable by the scan page (allowJs).

   NON-FABRICATING BY CONSTRUCTION: it only ever returns lines that are actually
   in the snapshot with a real book price. Nothing is suggested, interpolated,
   or rounded to a nearest. A player+stat the board didn't price returns [].
   ============================================================ */

const { nameKey } = require('./playerName');

/**
 * indexPricedLines(grades) — snapshot grades → Map(playerKey|stat → [rows]).
 * A row is kept ONLY if it carries a real book price — a graded prop with no
 * market is not a priceable line to surface.
 */
function indexPricedLines(grades) {
  const idx = new Map();
  for (const g of Array.isArray(grades) ? grades : []) {
    if (!g) continue;
    const book = g.book_odds;
    if (book == null || book === '') continue; // no market → not surfaceable
    const player = g.player_name || g.player;
    const stat = String(g.stat_type || g.stat || '').toLowerCase();
    if (!player || !stat) continue;
    const line = Number(g.line);
    if (!Number.isFinite(line)) continue;
    const key = `${nameKey(player)}|${stat}`;
    const side = String(g.direction || g.side || 'over').toLowerCase() === 'under' ? 'under' : 'over';
    const rows = idx.get(key) || [];
    // Dedupe on line+side — one snapshot shouldn't carry the same line twice,
    // but be defensive so the chip list never repeats.
    if (!rows.some((r) => r.line === line && r.direction === side)) {
      rows.push({ line, direction: side, book_odds: Number(book) });
    }
    idx.set(key, rows);
  }
  return idx;
}

/**
 * pricedLinesFor(index, player, stat) — the priced lines for an EXACT
 * player+stat. A different stat priced for the same player returns nothing for
 * the picked stat; an off-slate player returns nothing. Sorted by line.
 */
function pricedLinesFor(index, player, stat) {
  if (!index || !player || !stat) return [];
  const key = `${nameKey(player)}|${String(stat).toLowerCase()}`;
  const rows = index.get(key) || [];
  return [...rows].sort((a, b) => a.line - b.line);
}

module.exports = { indexPricedLines, pricedLinesFor };
