import 'dotenv/config';

import pool from '../db';
import { assessPlayerPropClvFit } from '../services/player-prop-clv-profile';

type PropRow = {
  id: string;
  prop_stat: string | null;
  direction: string | null;
  rec_line: number | null;
  rec_odds: number | null;
  model_confidence: number | null;
  v2_eligible: boolean | null;
};

async function main(): Promise<void> {
  const { rows } = await pool.query<PropRow>(
    `SELECT id, prop_stat, direction, rec_line, rec_odds, model_confidence, v2_eligible
     FROM rm_pick_clv
     WHERE league = 'mlb'
       AND pick_type = 'player_prop'`,
  );

  let changed = 0;
  let eligible = 0;

  for (const row of rows) {
    const nextEligible = assessPlayerPropClvFit({
      league: 'mlb',
      normalizedStatType: row.prop_stat,
      recommendation: row.direction,
      confidenceFactor: row.model_confidence,
      odds: row.rec_odds,
      marketLine: row.rec_line,
    }).eligible;

    if (nextEligible) eligible++;

    if (row.v2_eligible === nextEligible) continue;

    await pool.query(
      `UPDATE rm_pick_clv
       SET v2_eligible = $2
       WHERE id = $1`,
      [row.id, nextEligible],
    );
    changed++;
  }

  console.log(JSON.stringify({
    audited: rows.length,
    changed,
    eligible,
    ineligible: rows.length - eligible,
  }));
}

main()
  .catch((error) => {
    console.error('[repair-mlb-prop-eligibility] failed', error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await pool.end().catch(() => undefined);
  });
