// engine/detectors/k3s-detector.ts — K3s lightweight Kubernetes cluster detection (SPEC-033 TD-P14-01)
// Detects K3s via config files, kubeconfig context, and directory structures.
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { glob } from 'glob';
// === Detection signals ===
/** Explicit config file paths that indicate K3s is in use. */
const K3S_PATHS = [
    'k3s.yaml',
    'k3s-config.yaml',
    'k3s-config.yml',
    '.k3s/config.yaml',
    '.k3s/config.yml',
];
/** Directories that indicate K3s is in use. */
const K3S_DIRS = ['k3s/', '.k3s/'];
/** Glob patterns for kubeconfig files that might contain a k3s context. */
const KUBECONFIG_PATTERNS = ['kubeconfig*.yaml', 'kubeconfig*.yml', '.kube/config'];
/** Content substring that identifies a K3s kubeconfig context. */
const K3S_KUBECONFIG_MARKER = 'k3s';
// === Public API ===
/**
 * Detects whether a project uses K3s as its Kubernetes orchestrator.
 *
 * Checks:
 * 1. Explicit K3s config files (k3s.yaml, k3s-config.yaml, .k3s/)
 * 2. Kubeconfig files containing a "k3s" context reference
 */
export async function detectK3s(projectPath) {
    // Check explicit config file paths
    for (const p of K3S_PATHS) {
        if (await fileExists(join(projectPath, p))) {
            return true;
        }
    }
    // Check K3s directories (presence of directory indicates K3s usage)
    for (const dir of K3S_DIRS) {
        if (await fileExists(join(projectPath, dir))) {
            return true;
        }
    }
    // Check kubeconfig files for k3s context references
    const kubeconfigFound = await detectK3sInKubeconfig(projectPath);
    if (kubeconfigFound) {
        return true;
    }
    return false;
}
// === Internal helpers ===
async function detectK3sInKubeconfig(projectPath) {
    for (const pattern of KUBECONFIG_PATTERNS) {
        try {
            const matches = await glob(pattern, { cwd: projectPath, nodir: true });
            for (const match of matches) {
                const hasK3s = await fileContains(join(projectPath, match), K3S_KUBECONFIG_MARKER);
                if (hasK3s) {
                    return true;
                }
            }
        }
        catch {
            // ignore glob errors
        }
    }
    return false;
}
async function fileExists(filePath) {
    try {
        await readFile(filePath, 'utf-8');
        return true;
    }
    catch {
        return false;
    }
}
async function fileContains(filePath, substring) {
    try {
        const content = await readFile(filePath, 'utf-8');
        return content.includes(substring);
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=k3s-detector.js.map