import * as fs from 'node:fs';
import * as path from 'node:path';
const ENV_VAR_PATTERNS = [
    // JS/TS: process.env.VAR_NAME
    /process\.env\.([A-Z_][A-Z0-9_]*)/g,
    // Python: os.environ['VAR'] or os.environ.get('VAR')
    /os\.environ(?:\.get)?\s*\(\s*['"]([A-Z_][A-Z0-9_]*)['"]/g,
    // Python: os.getenv('VAR')
    /os\.getenv\s*\(\s*['"]([A-Z_][A-Z0-9_]*)['"]/g,
    // Go: os.Getenv("VAR")
    /os\.Getenv\s*\(\s*['"]([A-Z_][A-Z0-9_]*)['"]/g,
    // Rust: std::env::var("VAR")
    /env::var\s*\(\s*['"]([A-Z_][A-Z0-9_]*)['"]/g,
];
const FEATURE_FLAG_PATTERNS = [
    // FEATURE_* env vars
    /\b(FEATURE_[A-Z0-9_]+)\b/g,
    // FF_* env vars
    /\b(FF_[A-Z0-9_]+)\b/g,
    // LaunchDarkly
    /ldClient\.(?:variation|boolVariation|stringVariation)\s*\(\s*['"]([^'"]+)['"]/g,
    // Unleash
    /unleash\.isEnabled\s*\(\s*['"]([^'"]+)['"]/g,
    // Generic: isFeatureEnabled('name')
    /isFeatureEnabled\s*\(\s*['"]([^'"]+)['"]/g,
    // flagsmith
    /flagsmith\.hasFeature\s*\(\s*['"]([^'"]+)['"]/g,
];
const INFRA_INDICATORS = {
    Dockerfile: 'Docker',
    'docker-compose.yml': 'Docker Compose',
    'docker-compose.yaml': 'Docker Compose',
    kubernetes: 'Kubernetes',
    k8s: 'Kubernetes',
    helm: 'Helm',
    terraform: 'Terraform',
    '.terraform': 'Terraform',
    pulumi: 'Pulumi',
    'serverless.yml': 'Serverless Framework',
    'serverless.yaml': 'Serverless Framework',
    'vercel.json': 'Vercel',
    'netlify.toml': 'Netlify',
    'fly.toml': 'Fly.io',
    'render.yaml': 'Render',
    'railway.json': 'Railway',
    Procfile: 'Heroku',
    'app.yaml': 'Google App Engine',
    '.github/workflows': 'GitHub Actions',
    '.gitlab-ci.yml': 'GitLab CI',
    Jenkinsfile: 'Jenkins',
    '.circleci': 'CircleCI',
    '.travis.yml': 'Travis CI',
    'bitbucket-pipelines.yml': 'Bitbucket Pipelines',
    'azure-pipelines.yml': 'Azure Pipelines',
    'cloudbuild.yaml': 'Google Cloud Build',
};
const IGNORE_DIRS = new Set([
    'node_modules',
    '.git',
    'dist',
    'build',
    'out',
    '.next',
    '.nuxt',
    'coverage',
    'vendor',
    '__pycache__',
]);
const SOURCE_EXTENSIONS = new Set([
    '.ts',
    '.tsx',
    '.js',
    '.jsx',
    '.mjs',
    '.cjs',
    '.py',
    '.go',
    '.java',
    '.kt',
    '.rs',
    '.rb',
]);
function collectAllFiles(dir) {
    const results = [];
    const queue = [dir];
    while (queue.length > 0) {
        const current = queue.pop();
        if (!current) {
            continue;
        }
        let entries;
        try {
            entries = fs.readdirSync(current, { withFileTypes: true });
        }
        catch {
            continue;
        }
        for (const entry of entries) {
            if (IGNORE_DIRS.has(entry.name)) {
                continue;
            }
            const full = path.join(current, entry.name);
            if (entry.isDirectory()) {
                queue.push(full);
            }
            else if (entry.isFile()) {
                results.push(full);
            }
        }
    }
    return results;
}
function isConfigFile(filePath) {
    const basename = path.basename(filePath);
    const ext = path.extname(filePath);
    if (basename.startsWith('.env')) {
        return true;
    }
    if (basename.includes('.config.')) {
        return true;
    }
    if (['.conf', '.cfg', '.ini', '.toml', '.yaml', '.yml'].includes(ext)) {
        return true;
    }
    if (['Dockerfile', 'Makefile', 'Procfile', 'Jenkinsfile'].includes(basename)) {
        return true;
    }
    if (basename === 'docker-compose.yml' || basename === 'docker-compose.yaml') {
        return true;
    }
    if (basename.endsWith('.json') &&
        (basename.startsWith('tsconfig') || basename === 'package.json')) {
        return true;
    }
    if (basename === 'go.mod' || basename === 'Cargo.toml') {
        return true;
    }
    if (basename === 'pyproject.toml' ||
        basename.startsWith('build.gradle') ||
        basename === 'pom.xml') {
        return true;
    }
    return false;
}
function extractEnvVarsFromEnvFile(filePath) {
    const vars = [];
    try {
        const content = fs.readFileSync(filePath, 'utf-8');
        const lines = content.split('\n');
        for (const line of lines) {
            const trimmed = line.trim();
            if (trimmed.startsWith('#') || !trimmed) {
                continue;
            }
            const match = /^([A-Z_][A-Z0-9_]*)\s*=/.exec(trimmed);
            if (match?.[1]) {
                vars.push(match[1]);
            }
        }
    }
    catch {
        // ignore
    }
    return vars;
}
function extractEnvVarsFromSource(content) {
    const vars = [];
    for (const pattern of ENV_VAR_PATTERNS) {
        const regex = new RegExp(pattern.source, pattern.flags);
        let match;
        while ((match = regex.exec(content)) !== null) {
            const v = match[1];
            if (v) {
                vars.push(v);
            }
        }
    }
    return vars;
}
function extractFeatureFlags(content) {
    const flags = [];
    for (const pattern of FEATURE_FLAG_PATTERNS) {
        const regex = new RegExp(pattern.source, pattern.flags);
        let match;
        while ((match = regex.exec(content)) !== null) {
            const f = match[1];
            if (f) {
                flags.push(f);
            }
        }
    }
    return flags;
}
function detectInfrastructure(files, rootDir) {
    const detected = new Set();
    for (const file of files) {
        const rel = path.relative(rootDir, file);
        const basename = path.basename(file);
        for (const [indicator, name] of Object.entries(INFRA_INDICATORS)) {
            if (basename === indicator || rel.includes(indicator)) {
                detected.add(name);
            }
        }
    }
    return [...detected].sort();
}
export function analyzeConfig(rootDir) {
    const allFiles = collectAllFiles(rootDir);
    const configFiles = [];
    const envVarSet = new Set();
    const flagSet = new Set();
    for (const file of allFiles) {
        const rel = path.relative(rootDir, file);
        if (isConfigFile(file)) {
            configFiles.push(rel);
        }
        // Extract env vars from .env files
        if (path.basename(file).startsWith('.env')) {
            for (const v of extractEnvVarsFromEnvFile(file)) {
                envVarSet.add(v);
            }
        }
        // Extract env vars and flags from source files
        if (SOURCE_EXTENSIONS.has(path.extname(file))) {
            try {
                const content = fs.readFileSync(file, 'utf-8');
                for (const v of extractEnvVarsFromSource(content)) {
                    envVarSet.add(v);
                }
                for (const f of extractFeatureFlags(content)) {
                    flagSet.add(f);
                }
            }
            catch {
                // ignore
            }
        }
    }
    const infrastructure = detectInfrastructure(allFiles, rootDir);
    return {
        configFiles: configFiles.sort(),
        envVars: [...envVarSet].sort(),
        featureFlags: [...flagSet].sort(),
        infrastructure,
    };
}
//# sourceMappingURL=config-analyzer.js.map