#!/usr/bin/env node

/**
 * Enhanced postinstall debugging and testing script
 * Tests both local and global NPM postinstall execution
 */

const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');

class PostinstallDebugger {
    constructor() {
        this.homeDir = os.homedir();
        this.logFile = path.join(this.homeDir, '.claude-pm-postinstall-debug.log');
        this.markerFile = path.join(this.homeDir, '.claude-pm-postinstall-marker');
        this.timestamp = new Date().toISOString();
    }

    log(message) {
        const logEntry = `[${this.timestamp}] ${message}\n`;
        console.log(message);
        
        try {
            fs.appendFileSync(this.logFile, logEntry);
        } catch (error) {
            console.error('Failed to write to log file:', error.message);
        }
    }

    detectInstallType() {
        const npmConfigPrefix = process.env.npm_config_prefix;
        const packagePath = process.cwd();
        const npmRoot = process.env.npm_config_globaldir || process.env.npm_root;
        
        // Enhanced global installation detection
        const globalIndicators = {
            npmPrefix: npmConfigPrefix && packagePath.includes(npmConfigPrefix),
            npmGlobalDir: npmRoot && packagePath.includes(npmRoot),
            nodeModulesGlobal: packagePath.includes('node_modules') && (
                packagePath.includes('/.npm-global/') ||
                packagePath.includes('/lib/node_modules/') ||
                packagePath.includes('/.nvm/versions/node/') ||
                packagePath.includes('/usr/local/lib/node_modules/') ||
                packagePath.includes('/opt/homebrew/lib/node_modules/')
            )
        };
        
        const isGlobal = Object.values(globalIndicators).some(Boolean);
        
        this.log('🔍 Installation Type Detection:');
        this.log(`   • NPM Prefix: ${npmConfigPrefix || 'NOT_SET'}`);
        this.log(`   • NPM Global Dir: ${npmRoot || 'NOT_SET'}`);
        this.log(`   • Package Path: ${packagePath}`);
        this.log(`   • Global Indicators: ${JSON.stringify(globalIndicators)}`);
        this.log(`   • Detected as: ${isGlobal ? 'GLOBAL' : 'LOCAL'}`);
        
        return isGlobal;
    }

    checkNpmVersion() {
        try {
            const npmVersion = execSync('npm --version', { encoding: 'utf8' }).trim();
            this.log(`   • NPM Version: ${npmVersion}`);
            
            // Check if this is a problematic npm version
            const majorVersion = parseInt(npmVersion.split('.')[0]);
            if (majorVersion >= 7) {
                this.log(`   ⚠️  WARNING: NPM ${majorVersion} has known postinstall issues with global installs`);
            }
            
            return npmVersion;
        } catch (error) {
            this.log(`   ❌ Failed to get NPM version: ${error.message}`);
            return null;
        }
    }

    createMarkerFile() {
        const markerContent = {
            timestamp: this.timestamp,
            nodeVersion: process.version,
            platform: os.platform(),
            installType: this.detectInstallType() ? 'global' : 'local',
            npmVersion: this.checkNpmVersion(),
            workingDirectory: process.cwd(),
            homeDirectory: this.homeDir,
            environment: {
                npm_config_prefix: process.env.npm_config_prefix,
                npm_config_globaldir: process.env.npm_config_globaldir,
                npm_root: process.env.npm_root,
                npm_config_global: process.env.npm_config_global
            }
        };
        
        try {
            fs.writeFileSync(this.markerFile, JSON.stringify(markerContent, null, 2));
            this.log(`✅ Created marker file: ${this.markerFile}`);
            return true;
        } catch (error) {
            this.log(`❌ Failed to create marker file: ${error.message}`);
            return false;
        }
    }

    async run() {
        this.log('🚀 Starting Enhanced Postinstall Debug Test');
        this.log(`   Platform: ${os.platform()}`);
        this.log(`   Node Version: ${process.version}`);
        this.log(`   Working Directory: ${process.cwd()}`);
        this.log('');
        
        // Detect installation type
        const isGlobal = this.detectInstallType();
        this.log('');
        
        // Check npm version
        this.log('📦 NPM Environment:');
        this.checkNpmVersion();
        this.log('');
        
        // Create marker file
        this.log('📝 Creating execution marker:');
        this.createMarkerFile();
        this.log('');
        
        // Check if .claude-pm directory exists
        const claudepmDir = path.join(this.homeDir, '.claude-pm');
        this.log('🏠 Home Directory Check:');
        this.log(`   • .claude-pm directory exists: ${fs.existsSync(claudepmDir)}`);
        this.log('');
        
        if (isGlobal) {
            this.log('⚠️  GLOBAL INSTALL DETECTED - postinstall may have limited functionality');
            this.log('   • Output may be suppressed');
            this.log('   • Scripts may not execute properly');
            this.log('   • Consider alternative deployment strategies');
        } else {
            this.log('✅ LOCAL INSTALL DETECTED - postinstall should work normally');
        }
        
        this.log('');
        this.log('✨ Enhanced postinstall debug test completed');
        this.log(`📁 Log file: ${this.logFile}`);
        this.log(`🔖 Marker file: ${this.markerFile}`);
    }
}

// Run the debugger
if (require.main === module) {
    const debugger = new PostinstallDebugger();
    debugger.run().catch(error => {
        console.error('❌ Debug test failed:', error);
        process.exit(1);
    });
}

module.exports = PostinstallDebugger;