// engine/advanced-testing/chaos-generator.ts — SPEC-049
// Generates LitmusChaos runbooks and validates Kubernetes project context.
import { getCdnUrl } from '../../config/version-defaults.js';
/** File patterns that indicate a Kubernetes project. */
const K8S_MANIFEST_PATTERNS = [
    'deployment.yaml',
    'deployment.yml',
    'service.yaml',
    'service.yml',
    'values.yaml',
    'Chart.yaml',
    'kustomization.yaml',
    'kustomization.yml',
    'k8s/',
    'kubernetes/',
    'manifests/',
    'helm/',
];
/**
 * Detect if the project uses Kubernetes by checking file paths for k8s manifests.
 */
export function isKubernetesProject(files) {
    const filePaths = files.map((f) => f.toLowerCase());
    return K8S_MANIFEST_PATTERNS.some((pattern) => filePaths.some((f) => f.includes(pattern.toLowerCase())));
}
/** Generate a pod-delete chaos experiment entry. */
function makePodDeleteExperiment(namespace) {
    return {
        name: 'pod-delete-experiment',
        type: 'pod-delete',
        namespace,
        verificationSteps: [
            `kubectl get pods -n ${namespace} --watch`,
            'Wait for replacement pod to reach Running state (< 30s)',
            'curl -f http://<service-endpoint>/health -- expect HTTP 200',
            'Verify error rate in monitoring dashboard stays < 1% during recovery',
        ],
    };
}
/** Generate a network-latency chaos experiment entry. */
function makeNetworkLatencyExperiment(namespace) {
    return {
        name: 'network-latency-experiment',
        type: 'network-latency',
        namespace,
        verificationSteps: [
            `kubectl apply -f network-chaos.yaml -n ${namespace}`,
            'Verify circuit breaker activates: check logs for circuit_open=true',
            'Verify timeout error responses return within configured deadline',
            'Verify retry logic fires at most maxRetries times',
            `kubectl delete -f network-chaos.yaml -n ${namespace}`,
            'Verify service recovers without restart',
        ],
    };
}
/** Generate a node-failure chaos experiment entry. */
function makeNodeFailureExperiment(namespace) {
    return {
        name: 'node-failure-experiment',
        type: 'node-failure',
        namespace,
        verificationSteps: [
            'kubectl cordon <target-node>',
            'kubectl drain <target-node> --ignore-daemonsets --delete-emptydir-data',
            `kubectl get pods -n ${namespace} -o wide -- verify pods rescheduled to other nodes`,
            'Verify all replicas Running on remaining nodes within 60s',
            'curl -f http://<service-endpoint>/health -- expect HTTP 200',
            'kubectl uncordon <target-node>',
        ],
    };
}
/** Generate a cpu-stress chaos experiment entry. */
function makeCpuStressExperiment(namespace) {
    return {
        name: 'cpu-stress-experiment',
        type: 'cpu-stress',
        namespace,
        verificationSteps: [
            `kubectl apply -f cpu-stress.yaml -n ${namespace}`,
            'Monitor CPU throttling: kubectl top pods -n ' + namespace,
            'Verify p95 latency stays within SLA thresholds (check APM dashboard)',
            'Verify horizontal pod autoscaler activates if configured',
            `kubectl delete -f cpu-stress.yaml -n ${namespace}`,
            'Verify CPU usage returns to baseline within 2 minutes',
        ],
    };
}
/**
 * Generate a runbook of LitmusChaos experiments for the given namespace.
 * Returns 4 standard experiments: pod-delete, network-latency, node-failure, cpu-stress.
 */
export function generateChaosRunbook(namespace) {
    const ns = namespace || 'staging';
    return [
        makePodDeleteExperiment(ns),
        makeNetworkLatencyExperiment(ns),
        makeNodeFailureExperiment(ns),
        makeCpuStressExperiment(ns),
    ];
}
/**
 * Build a Markdown runbook document from the experiments.
 * Returns a string with LitmusChaos CLI commands and verification steps.
 */
export function buildChaosRunbookMarkdown(namespace, experiments) {
    const lines = [
        `# Chaos Engineering Runbook — ${namespace}`,
        '',
        '> Generated by Planu SPEC-049. Run experiments in staging only.',
        '> Prerequisites: LitmusChaos installed (https://litmuschaos.io), kubectl configured.',
        '',
        '## Setup',
        '',
        '```bash',
        '# Install LitmusChaos operator',
        `kubectl apply -f ${getCdnUrl('litmuschaos')}`,
        '',
        '# Verify installation',
        'kubectl get pods -n litmus',
        '```',
        '',
    ];
    for (const [i, exp] of experiments.entries()) {
        lines.push(`## Experiment ${i + 1}: ${exp.name}`);
        lines.push('');
        lines.push(`**Type:** \`${exp.type}\` | **Namespace:** \`${exp.namespace}\``);
        lines.push('');
        lines.push('### Verification Steps');
        lines.push('');
        for (const step of exp.verificationSteps) {
            lines.push(`${i + 1}. ${step}`);
        }
        lines.push('');
        lines.push('**Pass condition:** Service health check returns HTTP 200 within SLA window.');
        lines.push('');
    }
    lines.push('## References');
    lines.push('');
    lines.push('- https://litmuschaos.io/docs');
    lines.push('- https://chaos.cncf.io/ (CNCF Chaos Engineering Working Group)');
    lines.push('');
    return lines.join('\n');
}
//# sourceMappingURL=chaos-generator.js.map