#!/usr/bin/env node
/**
 * Cleanup orphan imports from deleted modules:
 * - @/lib/supabase
 * - @/lib/dual-database
 * - @/lib/sync-queue
 * - @/lib/data-source
 *
 * Strategy:
 * 1. Remove import lines
 * 2. Remove `if (supabaseAdmin) { ... }` sync blocks
 * 3. Remove `saveToBothDatabases(...)` calls (keeping the line's semicolon)
 * 4. Remove `syncToSupabase(...)` calls
 * 5. Remove `const supabase = supabaseAdmin;` aliases
 * 6. Remove `const clientError = checkSupabaseClient(supabaseAdmin);` and related checks
 */

import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';

const ROOT = path.resolve('.');

// Find files with orphan imports
const DELETED_MODULES = [
  "@/lib/supabase",
  "@/lib/dual-database",
  "@/lib/sync-queue",
  "@/lib/data-source",
];

function findFiles(pattern) {
  try {
    const result = execSync(
      `grep -rl "from '${pattern}'" app/ lib/ components/ 2>/dev/null | grep -v node_modules | grep -v __tests__`,
      { cwd: ROOT, encoding: 'utf-8' }
    );
    return result.trim().split('\n').filter(Boolean);
  } catch {
    return [];
  }
}

function cleanFile(filePath) {
  const fullPath = path.join(ROOT, filePath);
  let content = fs.readFileSync(fullPath, 'utf-8');
  const original = content;

  // 1. Remove import lines for deleted modules
  for (const mod of DELETED_MODULES) {
    // Single-line import
    content = content.replace(new RegExp(`^import\\s+.*from\\s+'${mod.replace(/\//g, '\\/')}';?\\n`, 'gm'), '');
    // Multi-line import
    content = content.replace(new RegExp(`^import\\s*\\{[^}]*\\}\\s*from\\s+'${mod.replace(/\//g, '\\/')}';?\\n`, 'gm'), '');
  }

  // 2. Remove `const supabase = supabaseAdmin;` aliases
  content = content.replace(/^const\s+supabase\s*=\s*supabaseAdmin;?\n/gm, '');

  // 3. Remove `if (supabaseAdmin) { ... }` blocks (multi-line)
  // These are sync blocks - the supabase sync is no longer needed
  // Pattern: if (supabaseAdmin) { <newlines and content> }
  let prevContent;
  do {
    prevContent = content;
    // Match if (supabaseAdmin) { ... } with nested braces up to 3 levels deep
    content = content.replace(
      /\n\s*if\s*\(\s*supabaseAdmin\s*\)\s*\{(?:[^{}]*(?:\{(?:[^{}]*(?:\{[^{}]*\})*[^{}]*)*\})*[^{}]*)*\}\n?/g,
      '\n'
    );
  } while (content !== prevContent);

  // 4. Remove `if (!supabaseAdmin) { return ...; }` guard blocks
  content = content.replace(
    /\n\s*if\s*\(\s*!supabaseAdmin\s*\)\s*\{[^}]*\}\n?/g,
    '\n'
  );

  // 5. Remove saveToBothDatabases(...) calls (standalone lines)
  content = content.replace(/^\s*(?:await\s+)?saveToBothDatabases\([\s\S]*?\);?\n/gm, '');

  // 6. Remove syncToSupabase(...) calls
  content = content.replace(/^\s*(?:await\s+)?syncToSupabase\([\s\S]*?\);?\n/gm, '');

  // 7. Remove saveAuditLogToBoth(...) calls
  content = content.replace(/^\s*(?:await\s+)?saveAuditLogToBoth\([\s\S]*?\);?\n/gm, '');

  // 8. Remove saveBookingToBoth / saveCustomerToBoth / etc. calls
  content = content.replace(/^\s*(?:await\s+)?save\w+ToBoth\([\s\S]*?\)(?:\.catch\(\(\)\s*=>\s*\{\}\))?;?\n/gm, '');

  // 9. Remove `queueFailedSync(...)` calls
  content = content.replace(/^\s*(?:await\s+)?queueFailedSync\([\s\S]*?\);?\n/gm, '');

  // 10. Remove `const clientError = checkSupabaseClient(supabaseAdmin);`
  content = content.replace(/^\s*const\s+clientError\s*=\s*checkSupabaseClient\(supabaseAdmin\);?\n/gm, '');
  content = content.replace(/^\s*if\s*\(\s*clientError\s*\)\s*(?:return\s+clientError|.*);?\n/gm, '');

  // 11. Remove getDataSource / dataSource routing
  content = content.replace(/^\s*const\s+(?:dataSource|source)\s*=\s*(?:await\s+)?getDataSource\(.*\);?\n/gm, '');

  // 12. Clean up double blank lines
  content = content.replace(/\n{3,}/g, '\n\n');

  if (content !== original) {
    fs.writeFileSync(fullPath, content, 'utf-8');
    return true;
  }
  return false;
}

// Main
let totalFixed = 0;
const allFiles = new Set();

for (const mod of DELETED_MODULES) {
  const files = findFiles(mod);
  files.forEach(f => allFiles.add(f));
}

console.log(`Found ${allFiles.size} files with orphan imports`);

for (const file of allFiles) {
  if (file.endsWith('.md')) {
    // Just remove the import line from markdown files
    const fullPath = path.join(ROOT, file);
    let content = fs.readFileSync(fullPath, 'utf-8');
    for (const mod of DELETED_MODULES) {
      content = content.replace(new RegExp(`.*from '${mod.replace(/\//g, '\\/')}'.*\\n`, 'g'), '');
    }
    fs.writeFileSync(fullPath, content);
    totalFixed++;
    console.log(`  Fixed (MD): ${file}`);
    continue;
  }

  try {
    const changed = cleanFile(file);
    if (changed) {
      totalFixed++;
      console.log(`  Fixed: ${file}`);
    } else {
      console.log(`  Skipped (no changes): ${file}`);
    }
  } catch (err) {
    console.error(`  ERROR: ${file}: ${err.message}`);
  }
}

console.log(`\nFixed ${totalFixed}/${allFiles.size} files`);
