import { shutdown } from './db.js';
import { scrapeDirectAcquisitions } from './scrapers/direct-acquisitions.js';
import { scrapePublicNotices } from './scrapers/public-notices.js';
import { matchAllEntities } from './matching/locality-matcher.js';
import { query } from './db.js';
import { monthsAgo } from './utils/date-ranges.js';

const mode = process.argv.find((a) => a.startsWith('--mode='))?.split('=')[1] || 'all';

async function refreshMaterializedView() {
  console.log('[MV] Refreshing uat_procurement_stats...');
  await query('REFRESH MATERIALIZED VIEW CONCURRENTLY seap.uat_procurement_stats');
  console.log('[MV] Done.');
}

async function main() {
  console.log(`\n=== SEAP Scraper — mode: ${mode} — ${new Date().toISOString()} ===\n`);

  try {
    switch (mode) {
      case 'da': {
        const count = await scrapeDirectAcquisitions();
        console.log(`\nDA: ${count} new records`);
        break;
      }
      case 'notices': {
        const count = await scrapePublicNotices();
        console.log(`\nNotices: ${count} new records`);
        break;
      }
      case 'backfill': {
        const startDate = monthsAgo(6);
        console.log(`Backfilling from ${startDate.toISOString()}`);
        const daCount = await scrapeDirectAcquisitions(startDate);
        const noticeCount = await scrapePublicNotices(startDate);
        console.log(`\nBackfill: ${daCount} DAs + ${noticeCount} notices`);
        break;
      }
      case 'match': {
        const result = await matchAllEntities();
        console.log(`\nMatching: ${result.matched} matched, ${result.unmatched} unmatched`);
        break;
      }
      case 'all': {
        // Incremental: scrape new data, match, refresh view
        const daCount = await scrapeDirectAcquisitions();
        const noticeCount = await scrapePublicNotices();
        const matchResult = await matchAllEntities();
        await refreshMaterializedView();
        console.log(`\nAll done: ${daCount} DAs, ${noticeCount} notices, ${matchResult.matched} newly matched`);
        break;
      }
      default:
        console.error(`Unknown mode: ${mode}. Use: da, notices, backfill, match, all`);
        process.exit(1);
    }
  } catch (err) {
    console.error('Fatal error:', err);
    process.exit(1);
  } finally {
    await shutdown();
  }
}

main();
