import { ti } from '../../i18n/index.js';
import { createBasicPhaseEvent } from '../../engine/phase-tracker.js';
import { buildWebConsultHints } from './helpers.js';
export function buildInitProjectResult(input) {
    const { knowledge, isUpdate } = input;
    const isEmpty = knowledge.language === 'unknown' && knowledge.framework === null && knowledge.apps.length <= 1;
    const webConsultHints = buildWebConsultHints(knowledge.language, knowledge.framework, knowledge.database);
    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: input.projectId,
        projectPath: input.projectPath,
        isUpdate: input.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: input.claudeMdRules.length,
        },
        webConsultHints,
        detectedPlatforms,
        platformHint,
        privacyConfig: {
            framework: input.privacyConfig.framework,
            defaultRetentionDays: input.privacyConfig.defaultRetentionDays,
            auditRetentionDays: input.privacyConfig.auditRetentionDays,
            dataProcessorsFound: input.privacyConfig.dataProcessors.length,
            dataProcessors: input.privacyConfig.dataProcessors.map((dp) => ({
                destination: dp.destination,
                type: dp.destinationType,
                requiresDPAReview: dp.requiresDPAReview,
            })),
        },
        completeness: {
            score: input.completeness.completenessScore,
            hasReadme: input.completeness.hasReadme,
            hasGitignore: input.completeness.hasGitignore,
            hasEnvExample: input.completeness.hasEnvExample,
            hasLicense: input.completeness.hasLicense,
            hasLinting: input.completeness.hasLinting,
            hasFormatting: input.completeness.hasFormatting,
            hasTesting: input.completeness.hasTesting,
            hasCiCd: input.completeness.hasCiCd,
            hasErrorTracking: input.completeness.hasErrorTracking,
            hasTypeChecking: input.completeness.hasTypeChecking,
            hasSecurityScanning: input.completeness.hasSecurityScanning,
            hasDocumentation: input.completeness.hasDocumentation,
        },
        modernArchitecturePatterns: input.modernPatterns.map((p) => ({
            name: p.name,
            confidence: p.confidence,
            indicators: p.indicators,
        })),
        dddDetected: input.dddConfig.detected,
        dddBoundedContexts: input.dddConfig.boundedContexts,
        agileProcess: input.agileDetection.process,
        agileConfidence: input.agileDetection.confidence,
        agileConfig: input.agileDetection.agileConfig,
        agileIndicators: input.agileDetection.indicators,
        orchestratorInfo: {
            orchestrator: input.orchestratorInfo.orchestrator,
            ...(input.orchestratorInfo.note ? { note: input.orchestratorInfo.note } : {}),
        },
        composeMultiplatform: input.composeMultiplatform.detected
            ? { crossPlatformEngine: input.composeMultiplatform.crossPlatformEngine }
            : null,
        message: isEmpty
            ? ti('project.emptyProject', {})
            : isUpdate
                ? ti('project.alreadyExists', {})
                : ti('project.initialized', {
                    language: knowledge.language,
                    framework: knowledge.framework ?? 'none',
                }),
        contextRequest: input.contextRequestPrompt
            ? {
                prompt: input.contextRequestPrompt,
                missingAreas: input.missingAreas,
                message: 'Please share the above documents so I can learn your project context.',
            }
            : null,
        envExample: input.envExampleGenerated !== null
            ? { generated: true, variablesCount: input.envExampleGenerated }
            : { generated: false, variablesCount: knowledge.envSetup.variables.length },
        beginnerEnvGuide: input.beginnerEnvGuide,
        recommendedSkills: input.recommendedSkills.map((s) => ({
            name: s.name,
            description: s.description,
            installCommand: s.installCommand,
            justification: s.justification,
        })),
        skillsAutoInstalled: input.skillsAutoInstalled,
        skillsSkipped: input.skillsSkipped,
        skillsPendingInstall: input.skillsPendingInstall,
        skillInstallHint: input.skillsPendingInstall.length > 0
            ? `Run skill_install to install recommended skills: ${input.skillsPendingInstall.join(', ')}`
            : null,
        planuConfig: input.planuConfigGenerated
            ? { generated: true, path: input.planuConfigPath }
            : { generated: false, path: input.planuConfigPath, note: 'Already exists' },
        generatedRules: {
            platform: input.platform,
            filePath: input.generatedRules.rulesFile.path,
            written: input.rulesWritten,
            additionalFilesWritten: input.additionalFilesWritten,
            skillsIncluded: input.recommendedSkills.length,
        },
        specMigration: input.migrationResult,
        specDiscovery: input.discoveryResult,
        specFolderMigration: input.folderMigrationResult,
        gitAutomation: {
            hooksInstalled: input.hooksInstalled,
            gitFlowType: input.gitFlowType,
            gitignoreUpdated: input.gitignoreUpdated,
            gitRepoDetected: input.gitRepoDetected ?? true,
            constitutionInitialized: input.constitutionInitialized,
            claudeMdUpdated: input.claudeMdUpdated,
            ...(input.gitRepoDetected === false
                ? {
                    gitNote: 'Note: No git repository detected. Consider running `git init` for version tracking.',
                }
                : {}),
        },
        whatsNew: input.whatsNew ?? null,
        autoCompletedSpecs: input.autoCompletedSpecs,
        lintScaffolding: {
            eslintCreated: input.eslintCreated,
            prettierCreated: input.prettierCreated,
            suggestions: input.lintSuggestions,
        },
        architectureRules: {
            written: input.architectureRulesWritten,
            skipped: input.architectureRulesSkipped,
        },
        projectHealth: input.healthReport
            ? {
                healthScore: input.healthReport.score,
                healthSummary: input.healthReport.summary,
                items: input.healthReport.items,
            }
            : null,
        feedbackHint: 'Found a bug or have a suggestion? Just say "I want to report a bug" or "I have a suggestion" and Planu will track it for you.',
        conventionScanStatus: input.conventionScanStatus ?? 'skipped',
        proactiveRulesInjected: input.proactiveRulesInjected ?? false,
        discoveredRegistrySkills: (input.discoveredRegistrySkills ?? []).slice(0, 3),
    };
    const framework = result.framework ?? 'no framework detected';
    const action = isUpdate ? 'updated' : 'initialized';
    const telemetryNote = input.telemetryOptInPrompt
        ? `\n\n---\n💡 **Help improve Planu** — run \`configure_telemetry\` with action=enable to share anonymous usage stats (no paths, no emails, no personal data). You can opt out anytime.`
        : '';
    const trialNote = '';
    const tokenTip = `\n\n💡 Token tip: Add CLAUDE_CODE_SUBAGENT_MODEL=haiku to your .env — makes all read-only subagents ` +
        `(search, grep, file reads) use Haiku instead of your session model (4–18x cheaper for those tasks).`;
    const narrative = ti('tools.init_project.success', { projectPath: result.projectPath }) +
        `\n\nDetected: **${result.language}** / ${framework} — project ${action}. ` +
        `Run \`create_spec\` to start planning your first feature.` +
        telemetryNote +
        trialNote +
        tokenTip;
    // SPEC-491: Build interactiveQuestions for decisions that require user input
    const interactiveQuestions = [];
    if (input.skillsPendingInstall.length > 0) {
        interactiveQuestions.push({
            question: `Install ${String(input.skillsPendingInstall.length)} recommended skill(s) now? (${input.skillsPendingInstall.join(', ')})`,
            header: 'Skills',
            multiSelect: false,
            options: [
                {
                    label: 'Yes, install now',
                    description: 'Runs skill_install for each recommended skill automatically.',
                },
                { label: 'Skip for now', description: 'You can install later with skill_install.' },
            ],
        });
    }
    if (input.contextRequestPrompt) {
        interactiveQuestions.push({
            question: input.contextRequestPrompt,
            header: 'Project Context',
            multiSelect: false,
            options: [
                {
                    label: 'Share context now',
                    description: 'Provide docs, README, or description so Planu can learn your project.',
                },
                { label: 'Skip', description: 'Continue without additional context.' },
            ],
        });
    }
    const hasInteractive = interactiveQuestions.length > 0;
    return {
        phaseEvent: createBasicPhaseEvent('init_project', 'completed', 100, 'initializing'),
        content: [
            { type: 'text', text: narrative },
            ...(hasInteractive
                ? [
                    {
                        type: 'text',
                        text: '⚡ INTERACTIVE — call AskUserQuestion now with the interactiveQuestions from structuredContent',
                    },
                ]
                : []),
        ],
        structuredContent: {
            ...result,
            ...(hasInteractive ? { interactiveQuestions } : {}),
        },
    };
}
//# sourceMappingURL=result-builder.js.map