/**
 * Fix Command - Automated Code Cleanup
 * Runs ESLint fix and other automated tools
 */
import { appConfig } from '../../config/index.js';
import { BaseCommand } from '../BaseCommand.js';
import { resolveNpmPath } from '../../common/index.js';
import { ErrorFactory } from '../../exceptions/ZintrustError.js';
import { execFileSync } from '../../node-singletons/child-process.js';
const runNpmScript = (cmd, args) => {
    const npmPath = resolveNpmPath();
    cmd.debug(`Executing: npm run ${args.join(' ')}`);
    execFileSync(npmPath, ['run', ...args], {
        stdio: 'inherit',
        encoding: 'utf8',
        env: appConfig.getSafeEnv(),
    });
};
const executeFix = (cmd, options) => {
    cmd.info('Starting automated code fixes...');
    try {
        const isDryRun = options['dryRun'] === true;
        cmd.info('Running ESLint fix...');
        try {
            runNpmScript(cmd, ['lint', '--', isDryRun ? '--fix-dry-run' : '--fix']);
        }
        catch (error) {
            ErrorFactory.createCliError('ESLint fix failed', error);
            cmd.warn('ESLint fix encountered some issues, continuing...');
        }
        cmd.info('Running Prettier format...');
        try {
            runNpmScript(cmd, ['format']);
        }
        catch (error) {
            ErrorFactory.createCliError('Prettier format failed', error);
            cmd.warn('Prettier format encountered some issues.');
        }
        cmd.success('Code fixes completed successfully!');
    }
    catch (error) {
        ErrorFactory.createCliError('Fix command failed', error);
        cmd.warn('Some fixes could not be applied automatically.');
    }
};
/**
 * Fix Command Factory
 */
export const FixCommand = Object.freeze({
    /**
     * Create a new fix command instance
     */
    create() {
        const addOptions = (command) => {
            command.option('--dry-run', 'Show what would be fixed without applying changes');
        };
        const cmd = BaseCommand.create({
            name: 'fix',
            description: 'Run automated code fixes',
            addOptions,
            execute: (options) => executeFix(cmd, options),
        });
        cmd.resolveNpmPath = () => resolveNpmPath();
        cmd.getSafeEnv = () => appConfig.getSafeEnv();
        cmd.runNpmExec = (args) => runNpmScript(cmd, args);
        return cmd;
    },
});
