#!/usr/bin/env node
// cleanup-planify-agents.mjs — one-shot maintenance.
//
// Archives the four leftover `planify-*` template agents that the old
// re-running seed loop installed alongside the `personal-*` ones, and
// renames `ati-planify-*` installation row IDs to `ati-personal-*` so
// the IDs match the project_id they actually point at. The Personal
// project + its `personal-*` agents are untouched.
//
// Usage:
//   node scripts/cleanup-planify-agents.mjs          # dry-run
//   node scripts/cleanup-planify-agents.mjs --apply  # archive + rename

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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DB_FILE = process.env.MADARX_DB_FILE
  ? path.resolve(process.env.MADARX_DB_FILE)
  : path.resolve(__dirname, '..', 'data', 'madarx.sqlite');
const WORKSPACE = path.resolve(__dirname, '..', 'workspace', 'agents');
const APPLY = process.argv.includes('--apply');

function main() {
  console.log(`[planify-cleanup] db: ${DB_FILE}`);
  console.log(`[planify-cleanup] mode: ${APPLY ? 'APPLY' : 'dry-run'}`);

  const db = new DatabaseSync(DB_FILE);
  db.exec('PRAGMA journal_mode=WAL;');
  db.exec('PRAGMA busy_timeout=10000;');

  const orphanAgents = db.prepare(
    `SELECT id, name FROM agents WHERE id LIKE 'planify-%' ORDER BY id`
  ).all();
  const renameInstalls = db.prepare(
    `SELECT id FROM agent_template_installations WHERE id LIKE 'ati-planify-%' ORDER BY id`
  ).all();

  console.log(`[planify-cleanup] orphan agents to archive: ${orphanAgents.length}`);
  orphanAgents.forEach(a => console.log(`  - ${a.id}  (${a.name})`));
  console.log(`[planify-cleanup] installation rows to rename: ${renameInstalls.length}`);
  renameInstalls.forEach(r => console.log(`  - ${r.id} -> ${r.id.replace('ati-planify-', 'ati-personal-')}`));

  if (!APPLY) {
    console.log('[planify-cleanup] dry run — pass --apply to write changes.');
    db.close();
    return;
  }

  db.exec('BEGIN IMMEDIATE');
  try {
    for (const a of orphanAgents) {
      db.prepare('UPDATE agents SET status = ? WHERE id = ?').run('archived', a.id);
      try {
        const src = path.join(WORKSPACE, a.id);
        const dst = path.join(WORKSPACE, '_archived', a.id);
        if (fs.existsSync(src)) {
          fs.mkdirSync(path.dirname(dst), { recursive: true });
          fs.renameSync(src, dst);
        }
      } catch (err) {
        console.warn(`[planify-cleanup] could not archive files for ${a.id}:`, err?.message || err);
      }
    }

    for (const r of renameInstalls) {
      const next = r.id.replace('ati-planify-', 'ati-personal-');
      const exists = db.prepare('SELECT 1 FROM agent_template_installations WHERE id = ?').get(next);
      if (exists) {
        db.prepare('DELETE FROM agent_template_installations WHERE id = ?').run(r.id);
        continue;
      }
      db.prepare('UPDATE agent_template_installations SET id = ? WHERE id = ?').run(next, r.id);
    }

    db.exec('COMMIT');
  } catch (err) {
    db.exec('ROLLBACK');
    console.error('[planify-cleanup] FAILED, rolled back:', err);
    process.exitCode = 1;
    db.close();
    return;
  }

  console.log('[planify-cleanup] done.');
  db.close();
}

main();
