#!/usr/bin/env node
/**
 * One-shot migration: reads .env.local, finds integration credentials, and
 * imports them into the encrypted secrets vault.
 *
 * Idempotent: if a secret is already in the vault with an active row, it is
 * skipped (not overwritten). Run with --force to overwrite.
 *
 * After verifying that tools work with vault-sourced credentials, manually
 * remove the migrated lines from .env.local. This script never deletes the
 * env file itself.
 *
 * Usage:
 *   node scripts/migrate-env-to-secrets.mjs [--force]
 */

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

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..');

// Allow override for tests (MADARX_DATA_DIR canonical; VILLA515_DATA_DIR legacy).
if (!process.env.MADARX_DATA_DIR && !process.env.VILLA515_DATA_DIR) {
  process.env.MADARX_DATA_DIR = path.join(root, 'data');
}

const { getSecret, setSecret, listSecrets } = await import('../lib/secrets.js');

// Integration credentials we migrate. Add new names here as new integrations
// are added. Local config vars (MADARX_*, CRON_*, HEARTBEAT_*, etc.) are NOT
// migrated — they stay in .env.local.
const CREDENTIAL_NAMES = [
  // Supabase
  'SUPABASE_ACCESS_TOKEN',
  'SUPABASE_URL',
  'SUPABASE_ANON_KEY',
  'SUPABASE_SERVICE_ROLE_KEY',
  // Vercel
  'VERCEL_TOKEN',
  'VERCEL_TEAM_ID',
  // Web / search
  'BRAVE_SEARCH_API_KEY',
  'FIRECRAWL_API_KEY',
  'FIRECRAWL_API_URL',
  'SEARXNG_URL',
];

const FORCE = process.argv.includes('--force');

function parseEnvFile(content) {
  const values = {};
  for (const line of String(content || '').split(/\r?\n/)) {
    const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
    if (!match) continue;
    let value = match[2] || '';
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
      value = value.slice(1, -1);
    }
    values[match[1]] = value;
  }
  return values;
}

function readEnvLocal() {
  const file = process.env.MADARX_ENV_FILE || path.join(root, '.env.local');
  try {
    return { file, content: fs.readFileSync(file, 'utf8') };
  } catch (err) {
    if (err.code === 'ENOENT') return { file, content: '' };
    throw err;
  }
}

async function main() {
  const { file, content } = readEnvLocal();
  const envValues = parseEnvFile(content);

  console.log('');
  console.log('madarX Secrets Migration');
  console.log('='.repeat(50));
  console.log(`Source: ${file}`);
  console.log(`Force overwrite: ${FORCE}`);
  console.log('');

  if (!content.trim()) {
    console.log('No .env.local found or file is empty. Nothing to migrate.');
    console.log('');
    return;
  }

  const results = { skipped: [], migrated: [], missing: [] };

  for (const name of CREDENTIAL_NAMES) {
    const value = envValues[name];
    if (!value || !value.trim()) {
      results.missing.push(name);
      continue;
    }

    // Check if already in vault.
    if (!FORCE) {
      let existing = null;
      try {
        existing = getSecret(name);
      } catch {
        // Vault may not be initialized yet — treat as not found.
      }
      if (existing) {
        results.skipped.push(name);
        continue;
      }
    }

    setSecret(name, value.trim(), { source: 'env_migration' });
    results.migrated.push(name);
  }

  // Summary.
  if (results.migrated.length) {
    console.log('Migrated:');
    for (const name of results.migrated) {
      console.log(`  [ok] ${name}`);
    }
    console.log('');
  }

  if (results.skipped.length) {
    console.log('Skipped (already in vault — use --force to overwrite):');
    for (const name of results.skipped) {
      console.log(`  [skip] ${name}`);
    }
    console.log('');
  }

  if (results.missing.length) {
    console.log('Not in .env.local (nothing to migrate):');
    for (const name of results.missing) {
      console.log(`  [--] ${name}`);
    }
    console.log('');
  }

  if (results.migrated.length === 0) {
    console.log('Nothing new migrated.');
  } else {
    console.log('-'.repeat(50));
    console.log('Next step: verify tools work, then remove these lines from .env.local:');
    console.log('');
    for (const name of results.migrated) {
      console.log(`  ${name}=...`);
    }
    console.log('');
    console.log('This script does NOT delete .env.local or remove lines from it.');
    console.log('Remove the migrated lines manually after verifying everything works.');
  }

  console.log('');
}

main().catch(err => {
  console.error('Migration failed:', err.message);
  process.exit(1);
});
