import { detectLegalFramework, detectThirdParties, buildDefaultPrivacyConfig, } from '../../engine/pii-detector.js';
import { readFile, writeFile, access } from 'node:fs/promises';
import { join } from 'node:path';
import { glob } from 'glob';
// SPEC-030: Privacy config detection -----------------------------------------
/**
 * Detects the applicable legal framework and third-party data processors
 * from the project's package.json and other codebase files.
 */
export async function detectProjectPrivacyConfig(projectPath) {
    let packageJson = '';
    try {
        packageJson = await readFile(join(projectPath, 'package.json'), 'utf-8');
    }
    catch {
        /* file not available */
    }
    let readmeText = '';
    try {
        readmeText = await readFile(join(projectPath, 'README.md'), 'utf-8');
    }
    catch {
        /* file not available */
    }
    const existingText = `${packageJson} ${readmeText}`;
    const framework = detectLegalFramework({ projectPath, existingText });
    const dataProcessors = detectThirdParties([packageJson]);
    return buildDefaultPrivacyConfig(framework, dataProcessors);
}
// SPEC-025 tech-debt: Auto-generate .env.example -------------------------
/**
 * Generates a `.env.example` file from the detected env variables.
 * Only writes the file if it does NOT already exist.
 * Returns the number of variables written, or null if file already existed.
 */
export async function maybeGenerateEnvExample(projectPath, variables) {
    const envExamplePath = join(projectPath, '.env.example');
    // Check if .env.example already exists
    try {
        await access(envExamplePath);
        return null; // already exists — skip
    }
    catch {
        // File does not exist — generate it
    }
    if (variables.length === 0) {
        return 0;
    }
    const lines = [
        '# Auto-generated by Planu init_project',
        '# Copy this file to .env and fill in your values',
        '',
    ];
    for (const variable of variables) {
        if (variable.description) {
            lines.push(`# ${variable.description}`);
        }
        if (variable.howToGet) {
            lines.push(`# How to get: ${variable.howToGet}`);
        }
        lines.push(`${variable.name}=your_value_here`);
        lines.push('');
    }
    await writeFile(envExamplePath, lines.join('\n'), 'utf-8');
    return variables.length;
}
// SPEC-025 tech-debt: Beginner env guide ------------------------------------
/**
 * Generates beginner-friendly step-by-step instructions for each env variable.
 * Only called when experienceLevel === 'beginner'.
 */
export function buildBeginnerEnvGuide(variables) {
    return variables.map((variable, index) => {
        const instructions = [];
        if (variable.howToGet) {
            instructions.push(variable.howToGet);
        }
        if (variable.dashboardUrl) {
            instructions.push(`Go to: ${variable.dashboardUrl}`);
        }
        if (variable.format) {
            instructions.push(`Expected format: ${variable.format}`);
        }
        instructions.push(`Set in your .env file as: ${variable.name}=<your-value>`);
        if (variable.sensitive) {
            instructions.push('IMPORTANT: Never commit this value to git — keep it secret!');
        }
        return {
            step: index + 1,
            variable: variable.name,
            title: variable.description || variable.name,
            instructions,
            dashboardUrl: variable.dashboardUrl,
        };
    });
}
/** Build web consultation hints for unknown detections */
export function buildWebConsultHints(language, framework, database) {
    const hints = [];
    if (language === 'unknown') {
        hints.push('Language not detected. Search project files for language-specific config files ' +
            'or check the repository README for stack information.');
    }
    if (framework === null || framework === 'unknown') {
        hints.push('Framework not detected. Check package.json dependencies, requirements.txt, ' +
            'or build config files to identify the framework.');
    }
    if (database === 'unknown') {
        hints.push('Database not detected. Look for database connection strings in .env files, ' +
            'ORM config files, or docker-compose services.');
    }
    return hints;
}
// SPEC-033 TD-P14-01+02: K3s/Nomad orchestrator detection -------------------
/**
 * Detects K3s or Nomad orchestrators from project files.
 * K3s: k3s.yaml present OR kubeconfig with "k3s+k3s1" in content.
 * Nomad: *.nomad, *.nomad.hcl, or nomad.hcl files present.
 */
export async function detectOrchestratorInfo(projectPath) {
    // Check for Nomad files first (*.nomad, *.nomad.hcl, nomad.hcl)
    let nomadFiles = [];
    try {
        nomadFiles = await glob('**/{*.nomad,*.nomad.hcl,nomad.hcl}', {
            cwd: projectPath,
            nodir: true,
            ignore: ['node_modules/**'],
        });
    }
    catch {
        /* glob errors are non-fatal */
    }
    if (nomadFiles.length > 0) {
        return {
            orchestrator: 'nomad',
            note: 'requires Consul for service discovery',
        };
    }
    // Check for k3s.yaml
    try {
        await access(join(projectPath, 'k3s.yaml'));
        return { orchestrator: 'k3s', note: null };
    }
    catch {
        /* k3s.yaml not found */
    }
    // Check kubeconfig files for k3s signature
    const kubeconfigCandidates = ['kubeconfig', 'kubeconfig.yaml', 'kubeconfig.yml', '.kube/config'];
    for (const candidate of kubeconfigCandidates) {
        try {
            const content = await readFile(join(projectPath, candidate), 'utf-8');
            if (content.includes('k3s+k3s1')) {
                return { orchestrator: 'k3s', note: null };
            }
        }
        catch {
            /* file not found or unreadable */
        }
    }
    return { orchestrator: null, note: null };
}
// SPEC-013 TD-P14-01: Compose Multiplatform iOS detection --------------------
/**
 * Detects Compose Multiplatform targeting iOS:
 * Signal: composeApp/ directory exists AND build.gradle.kts contains "compose-multiplatform".
 */
export async function detectComposeMultiplatform(projectPath) {
    // Check for composeApp/ directory
    try {
        const { stat } = await import('node:fs/promises');
        const composeAppStat = await stat(join(projectPath, 'composeApp'));
        if (!composeAppStat.isDirectory()) {
            return { detected: false, crossPlatformEngine: null };
        }
    }
    catch {
        return { detected: false, crossPlatformEngine: null };
    }
    // Check build.gradle.kts for compose-multiplatform
    let gradleContent = '';
    const gradleCandidates = [
        'build.gradle.kts',
        'composeApp/build.gradle.kts',
        'settings.gradle.kts',
    ];
    for (const candidate of gradleCandidates) {
        try {
            gradleContent += await readFile(join(projectPath, candidate), 'utf-8');
        }
        catch {
            /* file not found — continue */
        }
    }
    // Detect via compose-multiplatform plugin ID or org.jetbrains.compose group
    if (gradleContent.includes('compose-multiplatform') ||
        gradleContent.includes('org.jetbrains.compose')) {
        return { detected: true, crossPlatformEngine: 'compose-multiplatform-ios' };
    }
    return { detected: false, crossPlatformEngine: null };
}
//# sourceMappingURL=helpers.js.map