import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
const defaultRunner = (args, env) => {
    execFileSync('sops', args, { env, stdio: 'pipe' });
};
export function resolveSopsFiles(environment, operation) {
    const plain = `.env.${environment}`;
    const encrypted = `.env.${environment}.enc`;
    return operation === 'encrypt'
        ? { inputFile: plain, outputFile: encrypted }
        : { inputFile: encrypted, outputFile: plain };
}
export function executeSops(options) {
    const { environment, keyFile, operation, runner = defaultRunner } = options;
    const keyFilePath = resolve(keyFile);
    const { inputFile, outputFile } = resolveSopsFiles(environment, operation);
    if (!existsSync(inputFile)) {
        return {
            environment,
            message: `Input file not found: ${inputFile}`,
            outputFile,
            status: 'skipped',
        };
    }
    if (!existsSync(keyFilePath)) {
        throw new Error(`Key file not found: ${keyFilePath}`);
    }
    const args = [
        `--${operation}`,
        '--input-type',
        'binary',
        '--output-type',
        'binary',
        '--output',
        outputFile,
        inputFile,
    ];
    try {
        runner(args, { ...process.env, SOPS_AGE_KEY_FILE: keyFilePath });
    }
    catch (error) {
        if (isEnoentError(error)) {
            throw new Error('sops is not installed. Install it from https://github.com/getsops/sops');
        }
        const stderr = error instanceof Error && 'stderr' in error
            ? String(error.stderr)
            : String(error);
        throw new Error(`sops ${operation} failed for ${inputFile}: ${stderr}`);
    }
    return { environment, outputFile, status: 'success' };
}
function isEnoentError(error) {
    return (error instanceof Error &&
        'code' in error &&
        error.code === 'ENOENT');
}
