#!/usr/bin/env node
/**
 * Dependency Verification Script
 *
 * This script verifies all critical dependencies are installed and can be resolved.
 * Created: 2025-11-18
 * Issue: @headlessui/react was missing, causing compilation failure
 *
 * Usage: node scripts/verify-dependencies.js
 */

const fs = require('fs');
const path = require('path');

// ANSI color codes for terminal output
const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
};

console.log(`${colors.cyan}🔍 Verifying Dependencies...${colors.reset}\n`);

// Critical dependencies that must be present
const criticalDependencies = [
  '@headlessui/react',
  'next',
  'react',
  'react-dom',
  'next-auth',
  '@prisma/client',
  'tailwindcss',
  'typescript',
];

// Components that import critical dependencies
const componentsToCheck = [
  {
    path: 'components/dashboard/AccountDropdown.tsx',
    requiredDep: '@headlessui/react',
  },
  {
    path: 'components/dashboard/AccountSettingsModal.tsx',
    requiredDep: '@headlessui/react',
  },
];

let hasErrors = false;
let warnings = 0;

// Step 1: Check package.json
console.log(`${colors.blue}Step 1: Checking package.json...${colors.reset}`);
const packageJsonPath = path.join(process.cwd(), 'package.json');

if (!fs.existsSync(packageJsonPath)) {
  console.error(`${colors.red}❌ package.json not found!${colors.reset}`);
  process.exit(1);
}

const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

for (const dep of criticalDependencies) {
  const isInstalled =
    packageJson.dependencies?.[dep] || packageJson.devDependencies?.[dep];

  if (isInstalled) {
    console.log(`${colors.green}✅${colors.reset} ${dep} - v${isInstalled}`);
  } else {
    console.error(`${colors.red}❌${colors.reset} ${dep} - NOT FOUND in package.json`);
    hasErrors = true;
  }
}

// Step 2: Check if dependencies can be resolved
console.log(`\n${colors.blue}Step 2: Checking if dependencies can be resolved...${colors.reset}`);

for (const dep of criticalDependencies) {
  try {
    require.resolve(dep);
    console.log(`${colors.green}✅${colors.reset} ${dep} - can be resolved`);
  } catch (error) {
    console.error(`${colors.red}❌${colors.reset} ${dep} - CANNOT be resolved`);
    console.error(`   ${colors.yellow}→ Run: npm install${colors.reset}`);
    hasErrors = true;
  }
}

// Step 3: Check critical component imports
console.log(`\n${colors.blue}Step 3: Checking critical component imports...${colors.reset}`);

for (const component of componentsToCheck) {
  const componentPath = path.join(process.cwd(), component.path);

  if (!fs.existsSync(componentPath)) {
    console.warn(`${colors.yellow}⚠️${colors.reset}  ${component.path} - file not found`);
    warnings++;
    continue;
  }

  const content = fs.readFileSync(componentPath, 'utf-8');

  if (content.includes(component.requiredDep)) {
    try {
      require.resolve(component.requiredDep);
      console.log(
        `${colors.green}✅${colors.reset} ${component.path} - ${component.requiredDep} can be resolved`
      );
    } catch (error) {
      console.error(
        `${colors.red}❌${colors.reset} ${component.path} - ${component.requiredDep} CANNOT be resolved`
      );
      hasErrors = true;
    }
  }
}

// Step 4: Check node_modules directory
console.log(`\n${colors.blue}Step 4: Checking node_modules...${colors.reset}`);

const nodeModulesPath = path.join(process.cwd(), 'node_modules');
if (!fs.existsSync(nodeModulesPath)) {
  console.error(
    `${colors.red}❌ node_modules directory not found!${colors.reset}`
  );
  console.error(`   ${colors.yellow}→ Run: npm install${colors.reset}`);
  hasErrors = true;
} else {
  console.log(
    `${colors.green}✅${colors.reset} node_modules directory exists`
  );

  // Check for critical package directories
  for (const dep of ['@headlessui', 'next', 'react']) {
    const depPath = path.join(nodeModulesPath, dep);
    if (fs.existsSync(depPath)) {
      console.log(`${colors.green}✅${colors.reset} ${dep}/ directory exists`);
    } else {
      console.error(
        `${colors.red}❌${colors.reset} ${dep}/ directory not found`
      );
      hasErrors = true;
    }
  }
}

// Step 5: Check package-lock.json
console.log(`\n${colors.blue}Step 5: Checking package-lock.json...${colors.reset}`);

const packageLockPath = path.join(process.cwd(), 'package-lock.json');
if (!fs.existsSync(packageLockPath)) {
  console.warn(
    `${colors.yellow}⚠️  package-lock.json not found${colors.reset}`
  );
  console.warn(`   ${colors.yellow}→ Run: npm install to generate it${colors.reset}`);
  warnings++;
} else {
  try {
    JSON.parse(fs.readFileSync(packageLockPath, 'utf-8'));
    console.log(
      `${colors.green}✅${colors.reset} package-lock.json is valid JSON`
    );
  } catch (error) {
    console.error(
      `${colors.red}❌ package-lock.json is invalid JSON!${colors.reset}`
    );
    hasErrors = true;
  }
}

// Final summary
console.log(`\n${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}`);

if (hasErrors) {
  console.log(`\n${colors.red}❌ DEPENDENCY VERIFICATION FAILED${colors.reset}`);
  console.log(`\n${colors.yellow}Fix the issues above by running:${colors.reset}`);
  console.log(`   ${colors.cyan}npm install${colors.reset}`);
  console.log(`   ${colors.cyan}npm install @headlessui/react --legacy-peer-deps${colors.reset}`);
  process.exit(1);
} else if (warnings > 0) {
  console.log(
    `\n${colors.yellow}⚠️  ${warnings} warning(s) found${colors.reset}`
  );
  console.log(
    `${colors.green}✅ All critical dependencies are properly installed${colors.reset}`
  );
  process.exit(0);
} else {
  console.log(
    `\n${colors.green}✅ ALL CHECKS PASSED - Dependencies are properly installed${colors.reset}`
  );
  process.exit(0);
}
