// Session 43 — engine attaches grade-card intelligence fields (stat context +
// VYNDR intelligence) from the feature vector, and gradeAdapter maps them.

const { __internals } = require('../../src/services/intelligence/analyzeViaEngine1');
const { buildIntelFields, computeFormScore, matchupGradeFromRank } = __internals;
const { mapScanToGradeResult } = require('../../web/src/lib/gradeAdapter');

describe('computeFormScore', () => {
  it('trends above 70 when recent > baseline (hot)', () => {
    expect(computeFormScore({ l5_avg: 30, l20_avg: 24 })).toBeGreaterThan(70);
  });
  it('trends below 70 when recent < baseline (cold)', () => {
    expect(computeFormScore({ l5_avg: 18, l20_avg: 26 })).toBeLessThan(70);
  });
  it('undefined when there is no recent average', () => {
    expect(computeFormScore({})).toBeUndefined();
  });
  // Session 65 — UN-FABRICATE. This branch used to `return 75`: a hardcoded
  // constant rendered under the FORM label whenever the baseline was missing
  // or zero. With no baseline there is no ratio, so the field is absent and
  // the card's self-hiding intel section drops the row.
  it('undefined (never a hardcoded 75) when the baseline is missing or zero', () => {
    expect(computeFormScore({ l5_avg: 12 })).toBeUndefined();
    expect(computeFormScore({ l5_avg: 12, l20_avg: 0 })).toBeUndefined();
    expect(computeFormScore({ l5_avg: 12, l20_avg: 0, l10_avg: 0 })).toBeUndefined();
  });
});

describe('matchupGradeFromRank', () => {
  it('maps normalized opponent rank to a letter grade', () => {
    expect(matchupGradeFromRank(0.9)).toBe('A');
    expect(matchupGradeFromRank(0.55)).toBe('B+');
    expect(matchupGradeFromRank(0.1)).toBe('C');
    expect(matchupGradeFromRank(undefined)).toBeUndefined();
  });
});

describe('buildIntelFields', () => {
  it('builds stat context + form/usage/matchup/rest from features', () => {
    const f = buildIntelFields({ l20_avg: 26.9, l10_avg: 28.4, l5_avg: 30.1, usage_rate: 31.2, opp_rank_stat: 0.7, rest_days: 2 });
    expect(f.season_avg).toBe(26.9);
    expect(f.last10_avg).toBe(28.4);
    expect(f.form).toBeGreaterThan(70);
    expect(f.usage).toBe('31.2%');
    expect(f.matchup_grade).toBe('A');
    expect(f.rest).toBe('2d rest');
  });

  it('omits fields with no data (so the card sections self-hide)', () => {
    expect(buildIntelFields({})).toEqual({});
  });

  it('feeds straight into the grade card via gradeAdapter', () => {
    const engineLike = { player: 'Wemby', stat: 'points', line: 26.5, grade: 'A', ...buildIntelFields({ l20_avg: 26.9, l10_avg: 28.4, l5_avg: 30, usage_rate: 31.2, opp_rank_stat: 0.7 }) };
    const card = mapScanToGradeResult(engineLike);
    expect(card.statContext).toMatchObject({ season: '26.9', last10: '28.4' });
    expect(card.vyndrIntel.matchup).toBe('A');
    expect(card.vyndrIntel.usage).toBe('31.2%');
  });
});
