import { createLogger } from '@aztec/aztec.js/log';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
const logger = createLogger('e2e:k8s-utils');
function shellQuote(value) {
    // Single-quote safe shell escaping: ' -> '\''
    return `'${value.replace(/'/g, "'\\''")}'`;
}
function valuesToArgs(values) {
    return Object.entries(values).map(([key, value])=>typeof value === 'number' || typeof value === 'boolean' ? `--set ${key}=${value}` : `--set-string ${key}=${shellQuote(String(value))}`).join(' ');
}
export function createHelmCommand({ instanceName, helmChartDir, namespace, valuesFile, timeout, values, reuseValues = false }) {
    const valuesFileArgs = valuesFile ? `--values ${helmChartDir}/values/${valuesFile}` : '';
    const reuseValuesArgs = reuseValues ? '--reuse-values' : '';
    return `helm upgrade --install ${instanceName} ${helmChartDir} --namespace ${namespace} ${valuesFileArgs} ${reuseValuesArgs} --wait --timeout=${timeout} ${valuesToArgs(values)}`;
}
export async function execHelmCommand(args) {
    const helmCommand = createHelmCommand(args);
    logger.info(`helm command: ${helmCommand}`);
    const { stdout } = await execAsync(helmCommand);
    return stdout;
}
export async function getHelmReleaseStatus(instanceName, namespace) {
    try {
        const { stdout } = await execAsync(`helm list --namespace ${namespace} --all --filter '^${instanceName}$' --output json | cat`);
        const parsed = JSON.parse(stdout);
        const row = parsed.find((r)=>r.name === instanceName);
        return row?.status;
    } catch  {
        return undefined;
    }
}
export async function forceDeleteHelmReleaseRecord(instanceName, namespace, log) {
    const labelSelector = `owner=helm,name=${instanceName}`;
    const cmd = `kubectl delete secret -n ${namespace} -l ${labelSelector} --ignore-not-found=true`;
    (log ?? logger).warn(`Force deleting Helm release record: ${cmd}`);
    await execAsync(cmd).catch(()=>undefined);
}
export async function hasDeployedHelmRelease(instanceName, namespace) {
    try {
        const status = await getHelmReleaseStatus(instanceName, namespace);
        return status?.toLowerCase() === 'deployed';
    } catch  {
        return false;
    }
}
