#!/usr/bin/env node
// Purge `artifacts` DB rows whose on-disk file no longer exists.
//
// Usage:
//   node scripts/clean-ghost-artifacts.mjs            # dry-run, lists ghosts
//   node scripts/clean-ghost-artifacts.mjs --commit   # delete the ghost rows
//   node scripts/clean-ghost-artifacts.mjs --commit --project=personal

import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';

const DB_PATH = path.resolve('data/madarx.sqlite');
const COMMIT = process.argv.includes('--commit');
const projectArg = process.argv.find((a) => a.startsWith('--project='));
const projectFilter = projectArg ? projectArg.slice('--project='.length) : null;

if (!fs.existsSync(DB_PATH)) {
  console.error(`DB not found at ${DB_PATH}`);
  process.exit(1);
}

const db = new DatabaseSync(DB_PATH);
let q = 'SELECT id, project_id, title, path, kind, created_at FROM artifacts';
const params = [];
if (projectFilter) { q += ' WHERE project_id = ?'; params.push(projectFilter); }
q += ' ORDER BY created_at DESC';
const rows = db.prepare(q).all(...params);

const ghosts = rows.filter((r) => {
  if (!r.path) return true;
  try { return !fs.existsSync(path.resolve(r.path)); } catch { return true; }
});

console.log(`Scanned ${rows.length} artifact rows${projectFilter ? ` for project ${projectFilter}` : ''}.`);
console.log(`Ghost rows (no on-disk file): ${ghosts.length}`);
ghosts.slice(0, 50).forEach((r) => {
  console.log(`  ${r.created_at}  ${r.kind}  ${r.title}  →  ${r.path}`);
});
if (ghosts.length > 50) console.log(`  …and ${ghosts.length - 50} more`);

if (!ghosts.length) {
  console.log('Nothing to do.');
  process.exit(0);
}

if (!COMMIT) {
  console.log('\nDry-run. Re-run with --commit to delete these rows.');
  process.exit(0);
}

const delStmt = db.prepare('DELETE FROM artifacts WHERE id = ?');
const tx = db.prepare('BEGIN');
const cm = db.prepare('COMMIT');
tx.run();
let deleted = 0;
for (const r of ghosts) {
  delStmt.run(r.id);
  deleted += 1;
}
cm.run();
console.log(`Deleted ${deleted} ghost rows.`);
