import { beforeEach, describe, expect, it, vi } from 'vitest';

const poolQuery = vi.fn();
const loadPiffPropsForDate = vi.fn(() => ({}));
const getPiffPropsForGame = vi.fn(() => []);
const loadDigimonPicksForDate = vi.fn(() => ({}));
const getDigimonForGame = vi.fn(() => []);
const getDvpForMatchup = vi.fn(async () => ({ home: null, away: null }));
const calculateComposite = vi.fn();
const buildIntelligence = vi.fn();
const mapToLegacyComposite = vi.fn();

vi.mock('../../db', () => ({ default: { query: poolQuery, end: vi.fn() } }));
vi.mock('../piff', () => ({ loadPiffPropsForDate, getPiffPropsForGame }));
vi.mock('../digimon', () => ({ loadDigimonPicksForDate, getDigimonForGame }));
vi.mock('../dvp', () => ({ getDvpForMatchup }));
vi.mock('../composite-score', () => ({ calculateComposite }));
vi.mock('../rie', async () => {
  const actual = await vi.importActual<any>('../rie');
  return { ...actual, buildIntelligence, mapToLegacyComposite };
});

describe('backfill-composite compatibility', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.resetModules();
    delete process.env.RIE_ONLY;
    delete process.env.RIE_NATIVE_OUTPUT;
    poolQuery
      .mockResolvedValueOnce({
        rows: [{
          id: 'fc-1',
          event_id: 'evt-1',
          league: 'nba',
          home_team: 'Lakers',
          away_team: 'Celtics',
          confidence_score: 0.74,
          forecast_data: { value_rating: 8 },
        }],
      })
      .mockResolvedValueOnce({ rows: [{ home_short: 'LAL', away_short: 'BOS' }] })
      .mockResolvedValue({ rows: [] });
  });

  it('keeps legacy writes when RIE_ONLY is false', async () => {
    calculateComposite.mockReturnValue({
      compositeConfidence: 0.8,
      stormCategory: 4,
      modelSignals: { grok: { confidence: 0.74, valueRating: 8 }, piff: null, digimon: null, dvp: null },
      edgeBreakdown: { grokScore: 0.74, piffScore: 0.5, digimonScore: null, weights: { grok: 1 } },
      compositeVersion: 'v2',
    });

    const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as any);
    await import('../backfill-composite');

    const updateArgs = poolQuery.mock.calls.find((call) => String(call[0]).includes('UPDATE rm_forecast_cache'));
    expect(updateArgs).toBeDefined();
    expect(updateArgs![1][1]).toContain('"modelSignals"');
    exitSpy.mockRestore();
  });
});
