#!/usr/bin/env node

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

function copyRecursive(src, dest) {
    if (!fs.existsSync(src)) {
        return;
    }

    const stats = fs.statSync(src);
    
    if (stats.isDirectory()) {
        if (!fs.existsSync(dest)) {
            fs.mkdirSync(dest, { recursive: true });
        }
        
        const items = fs.readdirSync(src);
        items.forEach(item => {
            const srcPath = path.join(src, item);
            const destPath = path.join(dest, item);
            copyRecursive(srcPath, destPath);
        });
    } else {
        const destDir = path.dirname(dest);
        if (!fs.existsSync(destDir)) {
            fs.mkdirSync(destDir, { recursive: true });
        }
        
        // Force overwrite existing files
        try {
            fs.copyFileSync(src, dest);
        } catch (error) {
            // If copy fails, try to remove the destination first and retry
            if (fs.existsSync(dest)) {
                fs.unlinkSync(dest);
                fs.copyFileSync(src, dest);
            } else {
                throw error;
            }
        }
    }
}

function main() {
    try {
        const homeDir = os.homedir();
        const claudeDestDir = path.join(homeDir, '.claude');
        const claudeSrcDir = path.join(__dirname, '..', 'claude');
        
        if (!fs.existsSync(claudeSrcDir)) {
            console.log('Claude directory not found, skipping postinstall setup');
            return;
        }
        
        if (!fs.existsSync(claudeDestDir)) {
            fs.mkdirSync(claudeDestDir, { recursive: true });
            console.log('Created .claude directory in home folder');
        }
        
        copyRecursive(claudeSrcDir, claudeDestDir);
        console.log('Successfully copied claude configuration files to ~/.claude (existing files overwritten)');
        
    } catch (error) {
        console.error('Error during postinstall setup:', error.message);
        process.exit(1);
    }
}

if (require.main === module) {
    main();
}

module.exports = { main };