#!/usr/bin/env node

/**
 * Postinstall script for @polymorphism-tech/morph-spec
 *
 * Checks if morph-spec is accessible in PATH and warns users
 * if it's not (common issue with nvm-windows).
 */

import { execSync } from 'child_process';
import { platform } from 'os';
import chalk from 'chalk';

const isWindows = platform() === 'win32';

/**
 * Check if morph-spec command is in PATH
 */
function isMorphSpecInPath() {
  try {
    const command = isWindows ? 'where morph-spec' : 'which morph-spec';
    execSync(command, { stdio: 'ignore' });
    return true;
  } catch {
    return false;
  }
}

/**
 * Detect if nvm-windows is installed
 */
function isUsingNvmWindows() {
  if (!isWindows) return false;

  try {
    const path = process.env.PATH || '';
    return path.includes('nvm4w') || path.includes('\\nvm\\');
  } catch {
    return false;
  }
}

/**
 * Get npm global prefix
 */
function getNpmGlobalPrefix() {
  try {
    const prefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
    return prefix;
  } catch {
    return null;
  }
}

/**
 * Show installation success message
 */
function showSuccessMessage() {
  console.log('');
  console.log(chalk.green('✓ @polymorphism-tech/morph-spec installed successfully!'));
  console.log('');
  console.log(chalk.cyan('Quick start:'));
  console.log(chalk.white('  morph-spec init'));
  console.log(chalk.white('  morph-spec --help'));
  console.log('');
}

/**
 * Show PATH warning for nvm-windows users
 */
function showPathWarning() {
  console.log('');
  console.log(chalk.yellow('⚠ Warning: morph-spec command not found in PATH'));
  console.log('');

  if (isUsingNvmWindows()) {
    console.log(chalk.white('You are using nvm-windows, which does not automatically add'));
    console.log(chalk.white('npm global packages to your PATH.'));
    console.log('');
    console.log(chalk.cyan('Solution 1: Add npm global directory to PATH'));

    const prefix = getNpmGlobalPrefix();
    if (prefix) {
      console.log(chalk.white(`  Add this to your PATH: ${chalk.yellow(prefix)}`));
      console.log('');
      console.log(chalk.gray('  PowerShell (as Administrator):'));
      console.log(chalk.white(`    [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";${prefix}", "User")`));
      console.log('');
      console.log(chalk.gray('  Or manually via System Properties > Environment Variables'));
    }

    console.log('');
    console.log(chalk.cyan('Solution 2: Use npx (recommended)'));
    console.log(chalk.white('  npx @polymorphism-tech/morph-spec init'));
    console.log(chalk.white('  npx @polymorphism-tech/morph-spec --help'));
  } else {
    console.log(chalk.white('The morph-spec command was not found in your PATH.'));
    console.log('');
    console.log(chalk.cyan('Solution: Use npx instead'));
    console.log(chalk.white('  npx @polymorphism-tech/morph-spec init'));
    console.log(chalk.white('  npx @polymorphism-tech/morph-spec --help'));
  }

  console.log('');
  console.log(chalk.gray('For more help, see: https://github.com/lucasPolymorphism/morph-spec-framework#troubleshooting'));
  console.log('');
}

/**
 * Main postinstall check
 */
function main() {
  // Only show messages for global installs
  // Skip for local installs (when used as dependency)
  const isGlobalInstall = process.env.npm_config_global === 'true';

  if (!isGlobalInstall) {
    // Silent exit for local installs
    return;
  }

  // Give npm a moment to set up the symlinks
  setTimeout(() => {
    if (isMorphSpecInPath()) {
      showSuccessMessage();
    } else {
      showPathWarning();
    }
  }, 100);
}

main();
