/**
 * Lineup / role signals.
 *
 * Two derived inputs:
 *   getProjectedStarters: from ESPN summary (post-game or pregame) or
 *     yesterday's box score as a fallback. The poller already caches the
 *     summary; we just walk it.
 *   getLineupRole: maps a player to 'primary_handler' | 'secondary' |
 *     'role_player' based on usage signals. For now this is a coarse
 *     heuristic driven by usage_rate; the feature cache pulls a finer
 *     value once Engine 2 surfaces per-player usage.
 */

function rolesFromBoxScore(boxScore) {
  const home = [];
  const away = [];
  const teams = boxScore?.boxscore?.players || [];
  for (let i = 0; i < teams.length; i += 1) {
    const team = teams[i];
    const bucket = i === 0 ? home : away;
    const athletes = team?.statistics?.[0]?.athletes || [];
    for (const a of athletes) {
      if (!a?.starter) continue;
      const id = a?.athlete?.id || a?.id;
      const name = a?.athlete?.displayName || a?.athlete?.fullName;
      if (!id || !name) continue;
      bucket.push({
        playerId: String(id),
        name,
        position: a?.athlete?.position?.abbreviation ?? null,
      });
    }
  }
  return { home, away };
}

async function getProjectedStarters(sport, gameId, espnSummary) {
  if (!espnSummary) return { home: [], away: [] };
  const lineup = rolesFromBoxScore(espnSummary);
  // Add 'role' annotation — first starter on each side defaults to primary
  // handler. Once usage data is available we refine; for now this is the
  // ESPN-listed starting order.
  for (const side of ['home', 'away']) {
    lineup[side] = lineup[side].map((p, idx) => ({
      ...p,
      role: idx === 0 ? 'primary_handler' : idx <= 2 ? 'secondary' : 'role_player',
    }));
  }
  return lineup;
}

// Coarse classification from a precomputed usage rate (0-1). Caller has
// the rate via teamStatsCache or the Python game-log service.
function classifyByUsage(usageRate) {
  const u = Number(usageRate);
  if (!Number.isFinite(u)) return 'role_player';
  if (u >= 0.28) return 'primary_handler';
  if (u >= 0.18) return 'secondary';
  return 'role_player';
}

function roleValue(role) {
  if (role === 'primary_handler') return 1.0;
  if (role === 'secondary') return 0.5;
  return 0.0;
}

async function getLineupRole(_sport, _teamAbbr, _playerId, usageRate) {
  // Until usage rates feed in, the caller passes one explicitly. If they
  // don't, classifyByUsage returns 'role_player' (the safe default).
  return classifyByUsage(usageRate);
}

module.exports = {
  getProjectedStarters,
  getLineupRole,
  classifyByUsage,
  roleValue,
  rolesFromBoxScore,
};
