/**
 * One-off cleanup: repair track rows corrupted by an earlier buggy
 * `metadata_refresh` worker job.
 *
 * The bug ran on EVERY refresh and concatenated (no separator) corruption
 * markers directly onto the real values:
 *   - tracks.title  += ' (Enriched)'
 *   - tracks.artist += 'Unknown Artist'
 * Because it ran repeatedly, corruption can be stacked, e.g.
 *   title  = "Song (Enriched) (Enriched)"
 *   artist = "RealName Unknown ArtistUnknown Artist"
 *
 * The repair logic (PASS 1 authoritative rescan + PASS 2 defensive SQL strip,
 * plus issue tracking) now lives in IntegrityService.runSweep(). This script is
 * just a run-once-and-exit entry point that delegates to it, so the regex/rescan
 * logic is never duplicated. Safe to run multiple times (idempotent).
 */
import { Client as PgClient } from 'pg';
import { IntegrityService } from '../integrity.service.js';
import { queue } from '../queue.js';

async function main() {
  const pgClient = new PgClient({
    connectionString: process.env.DATABASE_URL,
  });

  await pgClient.connect();
  console.log('[Repair] Connected to PostgreSQL');

  const integrity = new IntegrityService(pgClient, queue);
  const summary = await integrity.runSweep();
  if (summary.aborted) {
    console.error(`[Repair] Sweep ABORTED by safety guard: ${summary.abortReason}`);
  } else {
    console.log(
      `[Repair] Done: detected=${summary.detected} fixed=${summary.fixed} needsReview=${summary.needsReview}`
    );
  }

  await pgClient.end();
  console.log('[Repair] Connection closed.');
}

main()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error('[Repair] Failed:', err);
    process.exit(1);
  });
