// SPEC-597-EXEMPT: canonical mapping (npm-package↔framework, keyword catalogue)
// — must enumerate framework names by design; no detection logic to migrate.
// Planu — Analyzer: Env Setup, MCP Discovery, and Stack Helpers
// Internal helpers extracted from analyzer.ts to keep file sizes manageable.
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { fileExists } from '../detection-utils.js';
// === Env Setup Analysis ===
export async function analyzeEnvSetup(projectPath, projectId) {
    const variables = [];
    const issues = [];
    for (const envFile of ['.env.example', '.env.local.example', '.env.sample']) {
        try {
            const content = await readFile(join(projectPath, envFile), 'utf-8');
            const parsed = parseEnvFile(content);
            variables.push(...parsed);
            break;
        }
        catch {
            // File doesn't exist
        }
    }
    const gitignoreHasEnv = await checkGitignoreForEnv(projectPath);
    const noEnvInGit = !(await fileExists(projectPath, '.env'));
    if (!gitignoreHasEnv) {
        issues.push({
            severity: 'critical',
            issue: '.env files are not in .gitignore',
            fix: 'Add .env* to .gitignore immediately',
        });
    }
    const security = {
        gitignoreHasEnv,
        noSecretsInCode: true,
        noEnvInGit,
        noSecretsInLogs: true,
        usesSecretManager: false,
        issues,
    };
    const missing = variables.filter((v) => v.required);
    return { projectId, variables, missing, security, setupSteps: [] };
}
function parseEnvFile(content) {
    const variables = [];
    for (const line of content.split('\n')) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#')) {
            continue;
        }
        const eqIndex = trimmed.indexOf('=');
        if (eqIndex === -1) {
            continue;
        }
        const name = trimmed.substring(0, eqIndex).trim();
        const value = trimmed.substring(eqIndex + 1).trim();
        const sensitive = /secret|key|password|token|api_key|private/i.test(name);
        variables.push({
            name,
            service: inferServiceFromEnvName(name),
            required: true,
            sensitive,
            description: '',
            howToGet: '',
            exampleValue: value || undefined,
            environments: ['development', 'staging', 'production'],
        });
    }
    return variables;
}
function inferServiceFromEnvName(name) {
    const upper = name.toUpperCase();
    if (upper.includes('SUPABASE')) {
        return 'supabase';
    }
    if (upper.includes('STRIPE')) {
        return 'stripe';
    }
    if (upper.includes('FIREBASE')) {
        return 'firebase';
    }
    if (upper.includes('AWS')) {
        return 'aws';
    }
    if (upper.includes('DATABASE') || upper.includes('DB_')) {
        return 'database';
    }
    if (upper.includes('REDIS')) {
        return 'redis';
    }
    if (upper.includes('SENTRY')) {
        return 'sentry';
    }
    if (upper.includes('GITHUB')) {
        return 'github';
    }
    if (upper.includes('OPENAI') || upper.includes('ANTHROPIC')) {
        return 'ai';
    }
    return 'app';
}
async function checkGitignoreForEnv(projectPath) {
    try {
        const content = await readFile(join(projectPath, '.gitignore'), 'utf-8');
        return content.includes('.env');
    }
    catch {
        return false;
    }
}
// === MCP Discovery ===
export async function discoverMcps(projectPath) {
    const mcps = [];
    const mcpConfigPaths = [
        join(projectPath, '.claude', 'settings.json'),
        join(projectPath, '.claude', 'settings.local.json'),
    ];
    for (const configPath of mcpConfigPaths) {
        try {
            const content = await readFile(configPath, 'utf-8');
            const config = JSON.parse(content);
            if (config.mcpServers && typeof config.mcpServers === 'object') {
                for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
                    const sc = serverConfig;
                    mcps.push({
                        name,
                        command: typeof sc.command === 'string' ? sc.command : '',
                        tools: Array.isArray(sc.tools) ? sc.tools : [],
                        relevantFor: [],
                    });
                }
            }
        }
        catch {
            // Config doesn't exist or is invalid
        }
    }
    return mcps;
}
// === Stack and Quality Helpers ===
export function buildStackList(language, framework, database, packageManager) {
    const stack = [language];
    if (framework) {
        stack.push(framework);
    }
    if (database !== 'unknown') {
        stack.push(database);
    }
    if (packageManager) {
        stack.push(packageManager);
    }
    return stack;
}
export function buildQualityProfile(linting, conventions) {
    const enabledCategories = [
        'solid',
        'clean-code',
        'architecture',
        'security',
        'error-handling',
    ];
    const principles = ['SOLID', 'Clean Code', 'Fail Fast', 'DRY'];
    let strictness = 'standard';
    // Auto-configure based on project rules
    if (conventions['ai-rules'] ?? conventions['commit-convention']) {
        strictness = 'strict';
    }
    if (linting.maturityScore >= 80) {
        enabledCategories.push('testing', 'performance');
    }
    const configuredLinterCount = linting.detectedLinters.filter((l) => l.status === 'configured').length;
    if (configuredLinterCount >= 3) {
        strictness = 'strict';
    }
    return { enabledCategories, customRules: [], principles, strictness };
}
//# sourceMappingURL=env-setup.js.map