#!/usr/bin/env tsx
/**
 * Manual cleanup script to complete Phase 1 migration
 * This fixes the multi-statement bug in the original migration
 */

import { createClient } from '@libsql/client';
import { config } from 'dotenv';

config();

const TURSO_URL = process.env.TURSO_URL!;
const TURSO_AUTH_TOKEN = process.env.TURSO_AUTH_TOKEN!;

const db = createClient({
  url: TURSO_URL,
  authToken: TURSO_AUTH_TOKEN,
});

async function cleanupPhase1() {
  console.log('\n🔧 Manual Phase 1 Cleanup - Fixing multi-statement bug\n');

  const statements = [
    // Drop learned_patterns indexes (these failed in original migration)
    { sql: 'DROP INDEX IF EXISTS idx_patterns_user_id', desc: 'Drop idx_patterns_user_id' },
    { sql: 'DROP INDEX IF EXISTS idx_patterns_type', desc: 'Drop idx_patterns_type' },

    // Drop redundant entities indexes
    { sql: 'DROP INDEX IF EXISTS idx_entities_user_id', desc: 'Drop idx_entities_user_id' },
    { sql: 'DROP INDEX IF EXISTS idx_entities_type', desc: 'Drop idx_entities_type' },
    { sql: 'DROP INDEX IF EXISTS idx_entities_name', desc: 'Drop idx_entities_name' },
    { sql: 'DROP INDEX IF EXISTS idx_entities_importance', desc: 'Drop idx_entities_importance' },

    // Drop redundant memories indexes
    { sql: 'DROP INDEX IF EXISTS idx_memories_user_id', desc: 'Drop idx_memories_user_id' },
    { sql: 'DROP INDEX IF EXISTS idx_memories_type', desc: 'Drop idx_memories_type' },
    { sql: 'DROP INDEX IF EXISTS idx_memories_archived', desc: 'Drop idx_memories_archived' },

    // Drop redundant interactions indexes
    { sql: 'DROP INDEX IF EXISTS idx_interactions_user_id', desc: 'Drop idx_interactions_user_id' },
    { sql: 'DROP INDEX IF EXISTS idx_interactions_created', desc: 'Drop idx_interactions_created' },
    { sql: 'DROP INDEX IF EXISTS idx_interactions_created_at', desc: 'Drop idx_interactions_created_at' },

    // Drop redundant api_usage_tracking indexes
    { sql: 'DROP INDEX IF EXISTS idx_usage_date', desc: 'Drop idx_usage_date' },
    { sql: 'DROP INDEX IF EXISTS idx_usage_provider_date', desc: 'Drop idx_usage_provider_date' },
  ];

  let successCount = 0;
  let skipCount = 0;

  for (const stmt of statements) {
    try {
      await db.execute(stmt.sql);
      console.log(`✅ ${stmt.desc}`);
      successCount++;
    } catch (error: any) {
      if (error.message.includes('no such index')) {
        console.log(`⏭️  ${stmt.desc} (already dropped)`);
        skipCount++;
      } else {
        console.log(`❌ ${stmt.desc}: ${error.message}`);
      }
    }
  }

  console.log(`\n📊 Summary: ${successCount} dropped, ${skipCount} already dropped\n`);
}

cleanupPhase1().catch(console.error);
