import 'dotenv/config';
import { copyFileSync, existsSync, readFileSync } from 'fs';
import { resolve } from 'path';
import { spawnSync } from 'child_process';

const dbType = process.env.DB_TYPE || 'sqlite';
const dbPath = process.env.DATABASE_URL || './data/spanglish.db';

function parseArgs(): { file?: string; yes?: boolean } {
  const args = process.argv.slice(2);
  const result: { file?: string; yes?: boolean } = {};
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '-y' || args[i] === '--yes') {
      result.yes = true;
    } else if (!args[i].startsWith('-')) {
      result.file = args[i];
    }
  }
  return result;
}

function importSqlite(backupPath: string): void {
  const targetPath = resolve(process.cwd(), dbPath);
  copyFileSync(backupPath, targetPath);
  console.log(`Restored from ${backupPath} to ${targetPath}`);
}

function importPostgres(backupPath: string): void {
  const connString = process.env.DATABASE_URL || 'postgresql://localhost:5432/spanglish';
  const sql = readFileSync(backupPath, 'utf-8');

  const result = spawnSync(
    'psql',
    [connString],
    {
      stdio: ['pipe', 'inherit', 'inherit'],
      input: sql,
    }
  );

  if (result.error) {
    console.error('psql failed. Ensure psql is installed and in PATH.');
    console.error(result.error.message);
    process.exit(1);
  }

  if (result.status !== 0) {
    process.exit(1);
  }

  console.log(`Restored from ${backupPath}`);
}

async function main() {
  const { file, yes } = parseArgs();

  if (!file) {
    console.error('Usage: npm run db:import -- <backup-file> [--yes]');
    console.error('Example: npm run db:import -- ./data/backups/spanglish-2025-03-07.db');
    process.exit(1);
  }

  const backupPath = resolve(process.cwd(), file);
  if (!existsSync(backupPath)) {
    console.error(`Backup file not found: ${backupPath}`);
    process.exit(1);
  }

  if (!yes) {
    console.log('WARNING: Import will overwrite the current database.');
    console.log('Stop the backend server before importing.');
    console.log('Press Ctrl+C to cancel, or run with --yes to skip this warning.');
    await new Promise((r) => setTimeout(r, 3000));
  }

  console.log(`Database type: ${dbType}`);
  if (dbType === 'sqlite') {
    importSqlite(backupPath);
  } else if (dbType === 'postgres') {
    importPostgres(backupPath);
  } else {
    console.error('Unknown DB_TYPE. Use sqlite or postgres.');
    process.exit(1);
  }
  process.exit(0);
}

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