import { PrismaClient } from '@prisma/client';
import path from 'path';
import fs from 'fs';
import { config } from 'dotenv';

async function verify() {
  console.log('--- Kord Recovery & Infrastructure Verification ---');

  // 1. Env Check
  const rootEnvPath = path.resolve(process.cwd(), '.env');
  console.log(`Checking .env at: ${rootEnvPath}`);
  if (fs.existsSync(rootEnvPath)) {
    config({ path: rootEnvPath });
    console.log('✅ .env file found and loaded.');
  } else {
    console.error('❌ .env file NOT found at root!');
  }

  const token = process.env.DISCORD_TOKEN;
  if (token) {
    console.log(`✅ DISCORD_TOKEN found (starts with: ${token.substring(0, 10)}...)`);
  } else {
    console.error('❌ DISCORD_TOKEN is missing!');
  }

  // 2. DB Check
  console.log('\nChecking Database Connection...');
  const { Pool } = require('pg');
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  
  try {
    const client = await pool.connect();
    console.log('✅ Connected to Database.');
    
    // Check ShardStatus table
    try {
      const res = await client.query("SELECT to_regclass('public.\"ShardStatus\"') as exists");
      if (res.rows[0].exists) {
        console.log(`✅ ShardStatus table exists.`);
      } else {
        console.error('❌ ShardStatus table NOT found in public schema!');
      }
    } catch (e: any) {
      console.error('❌ Error checking ShardStatus table:', e.message);
    } finally {
      client.release();
    }
  } catch (e: any) {
    console.error('❌ Database connection failed:', e.message);
  } finally {
    await pool.end();
  }

  // 3. gRPC Contract Check
  console.log('\nChecking gRPC Contracts...');
  try {
    const { kordProto, protoPath } = require(path.resolve(process.cwd(), 'packages/grpc-contracts/src/index'));
    console.log(`✅ gRPC Proto found at: ${protoPath}`);
    if (kordProto) {
      console.log('✅ kordProto loaded successfully.');
    }
  } catch (e: any) {
    console.error('❌ gRPC Contract loading failed:', e.message);
  }

  console.log('\n--- Verification Finished ---');
}

verify().catch(err => {
  console.error('Fatal error during verification:', err);
  process.exit(1);
});
