import { ti } from '../../i18n/index.js';
import { hashProjectPath, knowledgeStore, globalStore, licenseStore } from '../../storage/index.js';
import { getCurrentTier } from '../license-gate.js';
import { checkLimits } from '../../engine/license-validator.js';
import { analyzeProject, checkProjectCompleteness } from '../../engine/analyzer.js';
import { parseProjectQualityRules } from '../../engine/auditor-claude-md.js';
import { createBasicPhaseEvent } from '../../engine/phase-tracker.js';
import { detectModernPatterns, detectDdd } from '../../engine/architecture-pattern-detector.js';
import { detectAgileProcess } from '../../engine/agile-config-builder.js';
import { detectMissingAreas, buildRequestPrompt } from '../../engine/context-merger.js';
import { detectProjectPrivacyConfig, maybeGenerateEnvExample, buildBeginnerEnvGuide, buildWebConsultHints, detectOrchestratorInfo, detectComposeMultiplatform, } from './helpers.js';
import { fetchRecommendedSkills } from '../suggest-tooling/skills-fetcher.js';
import { generateRules, detectAgentPlatformFromFiles } from '../../engine/skill-generator.js';
export async function handleInitProject(params) {
    const { projectPath, locale, specLocation, hourlyRate, experienceLevel, userProfile } = params;
    try {
        const projectId = hashProjectPath(projectPath);
        // Check if project is already initialized
        const existing = await knowledgeStore.getKnowledge(projectId);
        const isUpdate = existing !== null;
        // License: check project limit only for new projects
        if (!isUpdate) {
            const tier = await getCurrentTier();
            const projectCount = await licenseStore.countActiveProjects();
            const limitCheck = checkLimits(tier, projectCount, 'maxProjects');
            if (!limitCheck.allowed) {
                return { content: [{ type: 'text', text: limitCheck.message }], isError: true };
            }
        }
        // Get global config for defaults
        const globalConfig = await globalStore.getGlobalConfig();
        const effectiveLocale = locale ?? existing?.locale ?? globalConfig.defaultLocale;
        const effectiveExperience = experienceLevel ?? existing?.experienceLevel ?? globalConfig.defaultExperienceLevel;
        // Run full project analysis
        const knowledge = await analyzeProject(projectPath, projectId, effectiveLocale, effectiveExperience);
        // Apply overrides
        if (specLocation) {
            knowledge.specLocation = specLocation;
        }
        if (userProfile) {
            knowledge.userProfile = userProfile;
        }
        // SPEC-026a: Compute project completeness score
        const completeness = await checkProjectCompleteness(projectPath);
        // Auto-configure qualityProfile from CLAUDE.md / .cursorrules (SPEC-010)
        const claudeMdRules = await parseProjectQualityRules(projectPath);
        if (claudeMdRules.length > 0) {
            knowledge.qualityProfile.customRules = [
                ...knowledge.qualityProfile.customRules,
                ...claudeMdRules,
            ];
        }
        // If hourly rate provided, update global config too
        if (hourlyRate !== undefined) {
            await globalStore.updateGlobalConfig({ hourlyRate });
        }
        // SPEC-033: Detect modern architecture patterns and agile process
        // SPEC-033 TD-P14-01+02: K3s/Nomad orchestrator + SPEC-013 TD-P14-01: Compose Multiplatform
        const [modernPatterns, dddConfig, agileDetection, orchestratorInfo, composeMultiplatform] = await Promise.all([
            detectModernPatterns(projectPath),
            detectDdd(projectPath),
            detectAgileProcess(projectPath),
            detectOrchestratorInfo(projectPath),
            detectComposeMultiplatform(projectPath),
        ]);
        // Save project knowledge
        await knowledgeStore.saveKnowledge(projectId, knowledge);
        // Auto-fetch recommended skills based on detected stack
        const recommendedSkills = await fetchRecommendedSkills(knowledge);
        // Auto-detect AI platform and generate rules with skills — zero user intervention
        const agentDetection = await detectAgentPlatformFromFiles(projectPath);
        const platform = agentDetection.platform;
        const constitution = await knowledgeStore.getConstitution(projectId);
        const generatedRules = await generateRules(platform, knowledge, constitution ?? undefined, {
            recommendedSkills,
        });
        // SPEC-036: Request context when knowledge is incomplete
        const missingAreas = detectMissingAreas(knowledge);
        let contextRequestPrompt = null;
        const needsContext = missingAreas.length > 0 && knowledge.contextRequested !== true;
        if (needsContext) {
            contextRequestPrompt = buildRequestPrompt(missingAreas, knowledge);
            // Persist the contextRequested flag without overwriting anything else
            await knowledgeStore.saveKnowledge(projectId, {
                ...knowledge,
                contextRequested: true,
            });
        }
        // SPEC-025 tech-debt: Auto-generate .env.example from detected env vars
        const envVars = knowledge.envSetup.variables;
        const envExampleGenerated = await maybeGenerateEnvExample(projectPath, envVars);
        // SPEC-025 tech-debt: Beginner env guide
        const beginnerEnvGuide = effectiveExperience === 'beginner' && envVars.length > 0
            ? buildBeginnerEnvGuide(envVars)
            : null;
        // SPEC-030: Detect legal framework and third-party data processors
        const privacyConfig = await detectProjectPrivacyConfig(projectPath);
        // Check for empty project → setup guide mode
        const isEmpty = knowledge.language === 'unknown' &&
            knowledge.framework === null &&
            knowledge.apps.length <= 1;
        // Generate web consultation hints for unknowns
        const webConsultHints = buildWebConsultHints(knowledge.language, knowledge.framework, knowledge.database);
        // Detect AI platform usage — suggest asking user if none detected
        const detectedPlatforms = Object.keys(knowledge.conventions).filter((k) => k.endsWith('-rules') || k === 'ai-rules');
        const platformHint = detectedPlatforms.length === 0
            ? 'No AI coding platform detected. Which platform are you using? ' +
                '(Claude Code, Cursor, Windsurf, Copilot, Cline, Codex, Antigravity, ' +
                'Gemini, Amazon Q, Devin, Aider, Continue, JetBrains Junie, etc.)'
            : null;
        const result = {
            projectId,
            projectPath,
            isUpdate,
            isEmpty,
            language: knowledge.language,
            languageVersion: knowledge.languageVersion,
            framework: knowledge.framework,
            frameworkVersion: knowledge.frameworkVersion,
            packageManager: knowledge.packageManager,
            database: knowledge.database,
            orm: knowledge.orm,
            architecture: knowledge.architecture.primary,
            secondaryPatterns: knowledge.architecture.secondary,
            apps: knowledge.apps.map((a) => ({
                name: a.name,
                type: a.type,
                language: a.language,
                framework: a.framework,
                orm: a.orm,
                architecture: a.architecture,
            })),
            monorepo: knowledge.monorepo,
            layers: knowledge.layers,
            stack: knowledge.stack,
            specLocation: knowledge.specLocation,
            locale: knowledge.locale,
            experienceLevel: knowledge.experienceLevel,
            userProfile: knowledge.userProfile ?? null,
            environments: knowledge.environments,
            linting: {
                maturityScore: knowledge.linting.maturityScore,
                configuredLinters: knowledge.linting.detectedLinters
                    .filter((l) => l.status === 'configured')
                    .map((l) => l.tool),
                conflicts: knowledge.linting.rulesConflicts.length,
            },
            conventions: knowledge.conventions,
            externalServices: knowledge.externalServices,
            tooling: knowledge.tooling,
            apiContracts: knowledge.apiContracts.map((c) => c.type),
            deploymentUnits: knowledge.architecture.deploymentUnits,
            availableMcps: knowledge.availableMcps.length,
            qualityProfile: {
                strictness: knowledge.qualityProfile.strictness,
                customRulesFromClaudeMd: claudeMdRules.length,
            },
            webConsultHints,
            detectedPlatforms,
            platformHint,
            // SPEC-030: Privacy config
            privacyConfig: {
                framework: privacyConfig.framework,
                defaultRetentionDays: privacyConfig.defaultRetentionDays,
                auditRetentionDays: privacyConfig.auditRetentionDays,
                dataProcessorsFound: privacyConfig.dataProcessors.length,
                dataProcessors: privacyConfig.dataProcessors.map((dp) => ({
                    destination: dp.destination,
                    type: dp.destinationType,
                    requiresDPAReview: dp.requiresDPAReview,
                })),
            },
            // SPEC-026a: Project completeness score
            completeness: {
                score: completeness.completenessScore,
                hasReadme: completeness.hasReadme,
                hasGitignore: completeness.hasGitignore,
                hasEnvExample: completeness.hasEnvExample,
                hasLicense: completeness.hasLicense,
                hasLinting: completeness.hasLinting,
                hasFormatting: completeness.hasFormatting,
                hasTesting: completeness.hasTesting,
                hasCiCd: completeness.hasCiCd,
                hasErrorTracking: completeness.hasErrorTracking,
                hasTypeChecking: completeness.hasTypeChecking,
                hasSecurityScanning: completeness.hasSecurityScanning,
                hasDocumentation: completeness.hasDocumentation,
            },
            // SPEC-033: Architecture pattern detection results
            modernArchitecturePatterns: modernPatterns.map((p) => ({
                name: p.name,
                confidence: p.confidence,
                indicators: p.indicators,
            })),
            dddDetected: dddConfig.detected,
            dddBoundedContexts: dddConfig.boundedContexts,
            // SPEC-033: Agile process detection
            agileProcess: agileDetection.process,
            agileConfidence: agileDetection.confidence,
            agileConfig: agileDetection.agileConfig,
            agileIndicators: agileDetection.indicators,
            // SPEC-033 TD-P14-01+02: K3s/Nomad orchestrator detection
            orchestratorInfo: {
                orchestrator: orchestratorInfo.orchestrator,
                ...(orchestratorInfo.note ? { note: orchestratorInfo.note } : {}),
            },
            // SPEC-013 TD-P14-01: Compose Multiplatform iOS detection
            composeMultiplatform: composeMultiplatform.detected
                ? { crossPlatformEngine: composeMultiplatform.crossPlatformEngine }
                : null,
            message: isEmpty
                ? ti('project.emptyProject', {})
                : isUpdate
                    ? ti('project.alreadyExists', {})
                    : ti('project.initialized', {
                        language: knowledge.language,
                        framework: knowledge.framework ?? 'none',
                    }),
            // SPEC-036: Include context request prompt if knowledge is incomplete
            contextRequest: contextRequestPrompt
                ? {
                    prompt: contextRequestPrompt,
                    missingAreas,
                    message: 'Please share the above documents so I can learn your project context.',
                }
                : null,
            // SPEC-025 tech-debt: .env.example auto-generation
            envExample: envExampleGenerated !== null
                ? { generated: true, variablesCount: envExampleGenerated }
                : { generated: false, variablesCount: envVars.length },
            // SPEC-025 tech-debt: Beginner env guide (only shown for beginner experience level)
            beginnerEnvGuide,
            // SPEC-022: Auto-detected skills from skills.sh — install automatically
            recommendedSkills: recommendedSkills.map((s) => ({
                name: s.name,
                description: s.description,
                installCommand: s.installCommand,
                justification: s.justification,
            })),
            // Auto-generated rules file — ready to save, no extra steps needed
            generatedRules: {
                platform,
                filePath: generatedRules.rulesFile.path,
                content: generatedRules.rulesFile.content,
                additionalFiles: generatedRules.additionalFiles.map((f) => ({
                    path: f.path,
                    content: f.content,
                })),
                skillsIncluded: recommendedSkills.length,
            },
        };
        return {
            phaseEvent: createBasicPhaseEvent('init_project', 'completed', 100, 'initializing'),
            content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=handler.js.map