'use strict';

/**
 * The VYNDR Lens (Session 60, night2/B) — THE RULE: no raw streak ever
 * renders alone. Every streak/hot-list row carries:
 *   1. what it was BUILT against (the streak-window opponents — real, from
 *      the game log),
 *   2. tonight's matchup (opponent + MLB opposing probable SP w/ ERA, from
 *      the free schedule/pitcher caches),
 *   3. difficulty vs the streak's diet (MLB: SP ERA vs league ~4.00),
 *   4. a one-line read composing the above.
 *
 * Interpreted data is the FREE layer; the grade on it stays paid. Every
 * field is real or absent — when we can't rate the matchup we say less,
 * we never invent. Pure module: callers supply tonight's context.
 */

// League-average SP ERA bands (MLB ~4.00 in the modern run environment).
const ERA_STEP_UP = 3.4;    // facing a SP at/below this = harder than average
const ERA_STEP_DOWN = 4.6;  // at/above this = softer than average

const token = (name) => String(name || '').toLowerCase().replace(/[^a-z0-9 ]/g, '').trim();
const mascot = (name) => { const t = token(name).split(' ').filter(Boolean); return t.length ? t[t.length - 1] : ''; };
const teamsMatch = (a, b) => {
  if (!a || !b) return false;
  return token(a) === token(b) || (mascot(a) !== '' && mascot(a) === mascot(b));
};

/**
 * Find tonight's game + opponent for a team from the cached schedule
 * (`schedule:{sport}:{date}` shape: [{ homeTeam:{name,abbreviation}, awayTeam, gameTime }]).
 */
function tonightFor(team, scheduleGames) {
  if (!team || !Array.isArray(scheduleGames)) return null;
  for (const g of scheduleGames) {
    const home = g.homeTeam || {};
    const away = g.awayTeam || {};
    if (teamsMatch(team, home.name) || teamsMatch(team, home.abbreviation)) {
      return { opponent: away.name || away.abbreviation || null, opponentAbbr: away.abbreviation || null, isHome: true, gameTime: g.gameTime || null };
    }
    if (teamsMatch(team, away.name) || teamsMatch(team, away.abbreviation)) {
      return { opponent: home.name || home.abbreviation || null, opponentAbbr: home.abbreviation || null, isHome: false, gameTime: g.gameTime || null };
    }
  }
  return null;
}

/**
 * Tonight's opposing probable SP for a team, from the probable-pitchers
 * games ([{ home: {team,pitcher,era}, away: {...} }]). The OPPOSING side.
 */
function opposingPitcherFor(team, pitcherGames) {
  if (!team || !Array.isArray(pitcherGames)) return null;
  for (const g of pitcherGames) {
    if (g && g.home && teamsMatch(team, g.home.team)) return g.away && g.away.pitcher ? g.away : null;
    if (g && g.away && teamsMatch(team, g.away.team)) return g.home && g.home.pitcher ? g.home : null;
  }
  return null;
}

function eraDifficulty(era) {
  const e = Number(era);
  if (!Number.isFinite(e) || e <= 0) return null;
  if (e <= ERA_STEP_UP) return 'step up';
  if (e >= ERA_STEP_DOWN) return 'step down';
  return 'neutral';
}

const isPitcherRow = (row) => row && (row.type === 'k_streak' || row.type === 'qs_streak');

/**
 * Build the lens for one streak/heat row. ctx = { scheduleGames, pitcherGames }.
 * Returns { builtVs, matchup, difficulty, read } — every field real or null.
 */
function buildLens(row, ctx = {}) {
  const lens = { builtVs: null, matchup: null, difficulty: null, read: null };
  if (!row) return lens;

  const opps = Array.isArray(row.opponents) ? row.opponents.filter(Boolean) : [];
  if (opps.length > 0) lens.builtVs = opps.slice(0, 4);

  const tonight = tonightFor(row.team, ctx.scheduleGames);
  if (tonight && tonight.opponent) {
    lens.matchup = `${tonight.isHome ? 'vs' : '@'} ${tonight.opponent}`;
    // MLB batter lens: the opposing probable SP is the matchup that matters.
    if (String(row.sport).toLowerCase() === 'mlb' && !isPitcherRow(row)) {
      const sp = opposingPitcherFor(row.team, ctx.pitcherGames);
      if (sp && sp.pitcher) {
        lens.matchup += ` · SP ${sp.pitcher}${sp.era != null ? ` (${sp.era} ERA)` : ''}`;
        lens.difficulty = eraDifficulty(sp.era);
      }
    }
  }

  // The one-line read: composed only from parts we actually have.
  const bits = [row.description];
  if (lens.builtVs) bits.push(`built vs ${lens.builtVs.join(', ')}`);
  if (lens.matchup) {
    if (lens.difficulty === 'step up') bits.push(`tonight ${lens.matchup} — a step up`);
    else if (lens.difficulty === 'step down') bits.push(`tonight ${lens.matchup} — a softer spot`);
    else bits.push(`tonight ${lens.matchup}`);
  }
  lens.read = bits.join('; ');
  return lens;
}

/** Attach the lens to every row (in place shape: { ...row, lens }). */
function applyLens(rows, ctx = {}) {
  return (rows || []).map((r) => ({ ...r, lens: buildLens(r, ctx) }));
}

module.exports = {
  buildLens,
  applyLens,
  tonightFor,
  opposingPitcherFor,
  __internals: { eraDifficulty, teamsMatch, ERA_STEP_UP, ERA_STEP_DOWN },
};
