/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { loadSettings } from '../../config/settings.js';
import { exitCli } from '../utils.js';
import * as fs from 'node:fs';
import * as path from 'node:path';
async function migrateHooks(options) {
    const { dryRun = false, confirm = false } = options;
    const settings = loadSettings();
    const userHooks = settings.merged.hooks;
    if (!userHooks || Object.keys(userHooks).length === 0) {
        console.log('No hooks found in user settings. Nothing to migrate.');
        return;
    }
    // Find the workspace root by looking for .llxprt directory
    let currentDir = process.cwd();
    let projectRoot = null;
    // Walk up directory tree to find .llxprt
    while (currentDir !== path.dirname(currentDir)) {
        const llxprtDir = path.join(currentDir, '.llxprt');
        if (fs.existsSync(llxprtDir) && fs.statSync(llxprtDir).isDirectory()) {
            projectRoot = currentDir;
            break;
        }
        currentDir = path.dirname(currentDir);
    }
    if (!projectRoot) {
        console.error('Error: Could not find .llxprt directory in current path.');
        console.error('Please run this command from within a project directory.');
        process.exit(1);
    }
    const projectSettingsPath = path.join(projectRoot, '.llxprt', 'settings.json');
    // Load or initialize project settings
    let projectSettings = {};
    if (fs.existsSync(projectSettingsPath)) {
        try {
            const content = fs.readFileSync(projectSettingsPath, 'utf-8');
            projectSettings = JSON.parse(content);
        }
        catch (error) {
            console.error(`Error reading ${projectSettingsPath}:`, error);
            process.exit(1);
        }
    }
    // Merge hooks, deduplicating by checking command/plugin equality
    const mergedHooks = {
        ...projectSettings.hooks,
    };
    let changesMade = false;
    for (const [eventName, definitions] of Object.entries(userHooks)) {
        // Skip the 'disabled' property which isn't an event
        if (eventName === 'disabled' || !Array.isArray(definitions))
            continue;
        const typedEventName = eventName;
        if (!mergedHooks[typedEventName]) {
            mergedHooks[typedEventName] = [];
            changesMade = true;
        }
        for (const definition of definitions) {
            // Check if this definition already exists in project hooks
            const exists = mergedHooks[typedEventName].some((existing) => JSON.stringify(existing) === JSON.stringify(definition));
            if (!exists) {
                mergedHooks[typedEventName].push(definition);
                changesMade = true;
            }
        }
    }
    if (!changesMade) {
        console.log('All hooks from user settings already exist in project settings.');
        return;
    }
    if (dryRun) {
        console.log('DRY RUN - Changes that would be made:');
        console.log('\nProject settings path:', projectSettingsPath);
        console.log('\nMerged hooks configuration:');
        console.log(JSON.stringify({ hooks: mergedHooks }, null, 2));
        return;
    }
    if (!confirm) {
        console.log('Migration preview:');
        console.log('\nProject settings path:', projectSettingsPath);
        console.log('\nMerged hooks configuration:');
        console.log(JSON.stringify({ hooks: mergedHooks }, null, 2));
        console.log('\nRe-run with --confirm to apply these changes.');
        return;
    }
    // Apply changes
    projectSettings.hooks = mergedHooks;
    // Ensure .llxprt directory exists
    const llxprtDir = path.dirname(projectSettingsPath);
    if (!fs.existsSync(llxprtDir)) {
        fs.mkdirSync(llxprtDir, { recursive: true });
    }
    // Write project settings
    try {
        fs.writeFileSync(projectSettingsPath, JSON.stringify(projectSettings, null, 2) + '\n', 'utf-8');
        console.log(`Successfully migrated hooks to ${projectSettingsPath}`);
    }
    catch (error) {
        console.error(`Error writing ${projectSettingsPath}:`, error);
        process.exit(1);
    }
}
export const migrateCommand = {
    command: 'migrate',
    describe: 'Migrate hooks from user settings to project-level config',
    builder: (yargs) => yargs
        .option('dry-run', {
        type: 'boolean',
        description: 'Show what would be migrated without making changes',
        default: false,
    })
        .option('confirm', {
        type: 'boolean',
        description: 'Confirm migration and apply changes',
        default: false,
    }),
    handler: async (argv) => {
        await migrateHooks(argv);
        await exitCli();
    },
};
//# sourceMappingURL=migrate.js.map