// Session 43 — slate adapter: player-grouped strips + MLB pitchers + BookChip.

const fs = require('fs');
const path = require('path');
const WEB = path.join(__dirname, '..', '..', 'web', 'src');
const adapter = require('../../web/src/lib/slateAdapter');

describe('groupPropsByPlayer', () => {
  it('groups props so each player appears once (name not repeated)', () => {
    const out = adapter.groupPropsByPlayer([
      { player: 'Austin Riley', team: 'ATL', stat: 'Hits', line: 1.5, side: 'Over', grade: 'A' },
      { player: 'Austin Riley', team: 'ATL', stat: 'Total Bases', line: 1.5, side: 'Over', grade: 'B+' },
      { player: 'Bryce Harper', team: 'PHI', stat: 'TB', line: 1.5, side: 'Over', grade: 'A' },
    ]);
    expect(out).toHaveLength(2);
    expect(out[0].player).toBe('Austin Riley');
    expect(out[0].props).toHaveLength(2);
    expect(out[0].props[0].side).toBe('O');
    expect(out[1].player).toBe('Bryce Harper');
  });

  it('attaches an archetype when a lookup is provided', () => {
    const out = adapter.groupPropsByPlayer(
      [{ player: 'Riley', stat: 'Hits', line: 1.5, side: 'Over', grade: 'A' }],
      () => ({ primary: 'BOMBER' }),
    );
    expect(out[0].archetype).toEqual({ primary: 'BOMBER' });
  });

  it('returns [] for empty / non-array input', () => {
    expect(adapter.groupPropsByPlayer(null)).toEqual([]);
    expect(adapter.groupPropsByPlayer([])).toEqual([]);
  });
});

describe('buildPlayerStripsFromProps — settled outcome passthrough (Session 55)', () => {
  it('attaches the settled outcome from the snapshot grade onto the prop', () => {
    const props = [{ player: 'Aaron Judge', stat_type: 'hits', line: 1.5 }];
    const gradeIndex = adapter.indexGrades([
      { player: 'Aaron Judge', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'A',
        gradedAt: { line: 1.5, timestamp: '2026-07-10T02:00:00Z' },
        outcome: { result: 'hit', actual: 2 } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {});
    expect(strips[0].props[0].outcome).toEqual({ result: 'hit', actual: 2 });
    expect(strips[0].props[0].grade).toBe('A');
  });

  it('leaves outcome null when the grade has not settled', () => {
    const props = [{ player: 'Aaron Judge', stat_type: 'hits', line: 1.5 }];
    const gradeIndex = adapter.indexGrades([
      { player: 'Aaron Judge', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'A',
        gradedAt: { line: 1.5, timestamp: '2026-07-10T02:00:00Z' } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {});
    expect(strips[0].props[0].outcome).toBeNull();
  });
});

describe('mapPitchers', () => {
  it('maps MLB probable pitchers to the GameCard shape', () => {
    const p = adapter.mapPitchers({
      sport: 'mlb',
      away: { probablePitcher: { name: 'Spencer Strider' } },
      home: { probablePitcher: { name: 'Zack Wheeler' } },
      awayPitcherERA: 3.21, homePitcherERA: 2.89,
    });
    expect(p.away.name).toBe('Spencer Strider');
    expect(p.away.era).toBe('3.21');
    expect(p.home.name).toBe('Zack Wheeler');
  });
  it('returns undefined for non-MLB or no probables', () => {
    expect(adapter.mapPitchers({ sport: 'nba' })).toBeUndefined();
    expect(adapter.mapPitchers({ sport: 'mlb' })).toBeUndefined();
  });
});

describe('mapScheduleToGameCards includes the new fields', () => {
  it('builds playerStrips + pitchers on each card', () => {
    const cards = adapter.mapScheduleToGameCards(
      [{ id: 'ATL-PHI', sport: 'mlb', awayTeam: { abbreviation: 'ATL', name: 'Braves' }, homeTeam: { abbreviation: 'PHI', name: 'Phillies' }, away: { probablePitcher: { name: 'Strider' } }, home: { probablePitcher: { name: 'Wheeler' } } }],
      {},
      [],
      [{ player: 'Austin Riley', team: 'ATL', stat: 'Hits', line: 1.5, grade: 'A', side: 'Over' }],
    );
    expect(cards[0].playerStrips[0].player).toBe('Austin Riley');
    expect(cards[0].pitchers.away.name).toBe('Strider');
  });
});

describe('legacy GameCard uses BookChip (brand colors)', () => {
  it('renders book chips instead of plain grey text', () => {
    const src = fs.readFileSync(path.join(WEB, 'components', 'GameCard.tsx'), 'utf8');
    expect(src).toContain('BookChip');
    expect(src).toContain('book={r.book}');
  });
});

// Session 59 (work-order 1.6) — THE JOIN INVARIANT. A prop can only attach
// to a game where the player's team is one of the two participants. The
// audit found Brandon Lowe (TB) rendered under MIL@PIT — a bad feed row the
// overlay happily displayed.
describe('buildPlayerStripsFromProps — game-participant join guard', () => {
  const GAME = { home: 'Milwaukee Brewers', away: 'Pittsburgh Pirates' };

  it('drops a graded prop whose player team is not in the game (TB ∉ MIL@PIT)', () => {
    const props = [{ player: 'Brandon Lowe', stat_type: 'hits', line: 1.5 }];
    const gradeIndex = adapter.indexGrades([
      { player: 'Brandon Lowe', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'A',
        team: 'Tampa Bay Rays', gradedAt: { line: 1.5, timestamp: '2026-07-10T02:00:00Z' } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {}, Date.now(), GAME);
    expect(strips).toEqual([]);
  });

  it('keeps a prop whose player team IS a participant + stamps the team', () => {
    const props = [{ player: 'Willy Adames', stat_type: 'hits', line: 1.5 }];
    const gradeIndex = adapter.indexGrades([
      { player: 'Willy Adames', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'B',
        team: 'Milwaukee Brewers', gradedAt: { line: 1.5, timestamp: '2026-07-10T02:00:00Z' } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {}, Date.now(), GAME);
    expect(strips).toHaveLength(1);
    expect(strips[0].team).toBe('Milwaukee Brewers');
  });

  it('keeps props with no team info (cannot verify ≠ wrong)', () => {
    const props = [{ player: 'Mystery Guy', stat_type: 'hits', line: 0.5 }];
    const strips = adapter.buildPlayerStripsFromProps(props, {}, {}, Date.now(), GAME);
    expect(strips).toHaveLength(1);
    expect(strips[0].props[0].awaiting).toBe(true);
  });

  // The invariant itself, as the suite-failing rule the work order asked for:
  it('INVARIANT: every rendered strip with a known team belongs to the game', () => {
    const props = [
      { player: 'Willy Adames', stat_type: 'hits', line: 1.5 },
      { player: 'Brandon Lowe', stat_type: 'hits', line: 1.5 },
      { player: 'Unknown Player', stat_type: 'runs', line: 0.5 },
    ];
    const gradeIndex = adapter.indexGrades([
      { player: 'Willy Adames', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'B', team: 'Milwaukee Brewers', gradedAt: { line: 1.5, timestamp: 'x' } },
      { player: 'Brandon Lowe', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'A', team: 'Tampa Bay Rays', gradedAt: { line: 1.5, timestamp: 'x' } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {}, Date.now(), GAME);
    const participants = ['milwaukee brewers', 'pittsburgh pirates'];
    for (const s of strips) {
      if (!s.team) continue;
      expect(participants).toContain(String(s.team).toLowerCase());
    }
    expect(strips.find((s) => String(s.team).toLowerCase() === 'tampa bay rays')).toBeUndefined();
  });
});

// Sánchez/Sanchez single-key regression (work-order 1.6 #4).
describe('diacritic variants resolve to ONE key across the slate', () => {
  it('an accented prop matches an unaccented snapshot grade (one strip, graded)', () => {
    const props = [{ player: 'Cristopher Sánchez', stat_type: 'strikeouts', line: 5.5 }];
    const gradeIndex = adapter.indexGrades([
      { player: 'Cristopher Sanchez', stat_type: 'strikeouts', line: 5.5, direction: 'over', grade: 'A',
        gradedAt: { line: 5.5, timestamp: 'x' } },
    ]);
    const strips = adapter.buildPlayerStripsFromProps(props, gradeIndex, {});
    expect(strips).toHaveLength(1);
    expect(strips[0].props[0].grade).toBe('A');
  });
});
