import { Command, Flags } from '@oclif/core';
import ora from 'ora';
import { loadConfig } from '../../deploy/domain/config.js';
import { resolveEnvironments } from '../../deploy/domain/plan-builder.js';
import { executeSops } from '../../deploy/domain/sops.js';
export default class Decrypt extends Command {
    static description = 'Decrypt .env.{env}.enc files using SOPS (age). Reads environments from aurora.yaml.';
    static examples = [
        '<%= config.bin %> env decrypt',
        '<%= config.bin %> env decrypt --env prod',
        '<%= config.bin %> env decrypt --key-file .keys/custom.txt',
    ];
    static flags = {
        config: Flags.string({
            char: 'c',
            default: './aurora.yaml',
            description: 'Path to aurora.yaml config file',
        }),
        env: Flags.string({
            description: 'Decrypt only this environment (e.g. dev, qa, prod)',
        }),
        'key-file': Flags.string({
            default: '.keys/age.txt',
            description: 'Path to age key file',
            env: 'SOPS_AGE_KEY_FILE',
        }),
    };
    async run() {
        const { flags } = await this.parse(Decrypt);
        const config = loadConfig(flags.config);
        const environments = resolveEnvironments(config, flags.env);
        let hasErrors = false;
        for (const env of environments) {
            const spinner = ora(`Decrypting .env.${env}.enc`).start();
            try {
                const result = executeSops({
                    environment: env,
                    keyFile: flags['key-file'],
                    operation: 'decrypt',
                });
                if (result.status === 'skipped') {
                    spinner.warn(result.message);
                }
                else {
                    spinner.succeed(`Decrypted → ${result.outputFile}`);
                }
            }
            catch (error) {
                hasErrors = true;
                spinner.fail(error instanceof Error ? error.message : String(error));
            }
        }
        if (hasErrors) {
            this.error('Some environments failed to decrypt.');
        }
    }
}
