import { knowledgeStore } from '../../storage/index.js';
import { buildLegalProfile } from '../../engine/legal-compliance/index.js';
import { createPlanuConfig, serializePlanuConfig, updatePlanuConfigWorkMode, } from '../../engine/planu-config-writer.js';
import { writeFile, access, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { checkWhatsNew } from './lifecycle-helpers.js';
import { detectGpaiUsage } from '../../engine/llm-security/gpai-detector.js';
/**
 * SPEC-131: Detect legal profile, save enriched knowledge, generate planu.json if missing,
 * and check What's New highlights.
 * SPEC-313: Persists workMode in planu.json when provided.
 */
export async function buildProjectConfig(projectPath, projectId, knowledge, workMode) {
    // SPEC-131: Detect legal compliance profile and re-save knowledge
    const legalProfile = buildLegalProfile(knowledge);
    // SPEC-535: Detect GPAI (foundation model) usage for EU AI Act Article 53-55 compliance
    let gpaiDetection = {
        usesFoundationModels: false,
        detectedSdks: [],
        providers: [],
    };
    try {
        gpaiDetection = await detectGpaiUsage(projectPath);
    }
    catch {
        /* best-effort — never block init_project */
    }
    const enrichedKnowledge = {
        ...knowledge,
        legalProfile,
        ...(gpaiDetection.usesFoundationModels && {
            gpaiSdks: gpaiDetection.detectedSdks,
            gpaiProviders: gpaiDetection.providers,
        }),
    };
    await knowledgeStore.saveKnowledge(projectId, enrichedKnowledge);
    // Generate planu.json if it doesn't exist yet
    const planuConfigPath = join(projectPath, 'planu.json');
    let planuConfigGenerated = false;
    try {
        await access(planuConfigPath);
    }
    catch {
        const planuConfig = createPlanuConfig(workMode);
        await writeFile(planuConfigPath, serializePlanuConfig(planuConfig), 'utf-8');
        planuConfigGenerated = true;
    }
    // SPEC-313: If planu.json already existed and workMode was passed, update it
    if (!planuConfigGenerated && workMode !== undefined) {
        await updatePlanuConfigWorkMode(planuConfigPath, workMode, readFile, writeFile);
    }
    // What's New: check version change and extract highlights (best-effort)
    const whatsNew = await checkWhatsNew(planuConfigPath);
    return { planuConfigPath, planuConfigGenerated, whatsNew };
}
//# sourceMappingURL=config-builder.js.map