"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupNextStepsReportPointerLine = exports.setupNextStepsReportRelativePath = void 0;
exports.buildSetupNextStepsModel = buildSetupNextStepsModel;
exports.renderSetupNextStepsMarkdown = renderSetupNextStepsMarkdown;
exports.renderSetupNextStepsConsole = renderSetupNextStepsConsole;
exports.writeSetupNextStepsReport = writeSetupNextStepsReport;
exports.refreshSetupNextStepsForWorkspace = refreshSetupNextStepsForWorkspace;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const ciWorkflowTemplates_1 = require("./ciWorkflowTemplates");
const adrScaffoldGeneration_1 = require("./adrScaffoldGeneration");
exports.setupNextStepsReportRelativePath = '.archpilot/reports/setup-next-steps.md';
exports.setupNextStepsReportPointerLine = 'Next steps updated: .archpilot/reports/setup-next-steps.md';
function ensureScore(value, min = 0, max = 100) {
    if (!Number.isFinite(value)) {
        return min;
    }
    return Math.min(max, Math.max(min, Math.round(value)));
}
async function pathExists(targetPath) {
    try {
        await node_fs_1.promises.access(targetPath);
        return true;
    }
    catch {
        return false;
    }
}
async function countContractFiles(contractsDir) {
    try {
        const entries = await node_fs_1.promises.readdir(contractsDir, { withFileTypes: true });
        let count = 0;
        for (const entry of entries) {
            if (entry.isFile() && entry.name.toLowerCase().endsWith('.contract.json')) {
                count += 1;
                continue;
            }
            if (entry.isDirectory()) {
                count += await countContractFiles(path.join(contractsDir, entry.name));
            }
        }
        return count;
    }
    catch {
        return 0;
    }
}
function countGovernedModulesFromConfig(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return 0;
    }
    const typed = value;
    const modules = typed.modules;
    if (Array.isArray(modules)) {
        return modules.filter((entry) => typeof entry === 'string' && entry.trim().length > 0).length;
    }
    if (modules && typeof modules === 'object' && !Array.isArray(modules)) {
        const moduleCount = Object.keys(modules).filter((key) => key.trim().length > 0).length;
        if (moduleCount > 0) {
            return moduleCount;
        }
    }
    const components = typed.components;
    if (Array.isArray(components)) {
        return components.filter((entry) => {
            if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
                return false;
            }
            const component = entry;
            return (typeof component.id === 'string' &&
                component.id.trim().length > 0 &&
                typeof component.path === 'string' &&
                component.path.trim().length > 0 &&
                component.path.trim() !== '.');
        }).length;
    }
    if (components && typeof components === 'object' && !Array.isArray(components)) {
        return Object.entries(components).filter(([key, value]) => {
            if (key.trim().length === 0 || !value || typeof value !== 'object' || Array.isArray(value)) {
                return false;
            }
            const component = value;
            return (typeof component.path === 'string' &&
                component.path.trim().length > 0 &&
                component.path.trim() !== '.');
        }).length;
    }
    return 0;
}
async function readGovernedModuleCount(workspaceRoot) {
    const architecturePath = path.join(workspaceRoot, '.archpilot', 'architecture.json');
    try {
        const raw = await node_fs_1.promises.readFile(architecturePath, { encoding: 'utf8' });
        return countGovernedModulesFromConfig(JSON.parse(raw));
    }
    catch {
        return 0;
    }
}
async function readValidationStatusFromWorkspace(workspaceRoot) {
    const validationStatusPath = path.join(workspaceRoot, '.archpilot', 'validation-status.json');
    let raw;
    try {
        raw = await node_fs_1.promises.readFile(validationStatusPath, { encoding: 'utf8' });
    }
    catch {
        return undefined;
    }
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object') {
            return undefined;
        }
        return parsed;
    }
    catch {
        return undefined;
    }
}
async function buildSetupSnapshot(workspaceRoot, validationStatus, options) {
    const archpilotDir = path.join(workspaceRoot, '.archpilot');
    const contractsDir = path.join(archpilotDir, 'contracts');
    const [hasArchitectureConfig, governedModuleCount, hasDependencyRules, hasLayerRules, hasContractsFolder, hasGithubCiWorkflow, detectedBaselineSnapshot, detectedDriftReport, detectedReviewReport] = await Promise.all([
        pathExists(path.join(archpilotDir, 'architecture.json')),
        readGovernedModuleCount(workspaceRoot),
        pathExists(path.join(archpilotDir, 'dependency-rules.json')),
        pathExists(path.join(archpilotDir, 'layer-rules.json')),
        pathExists(contractsDir),
        pathExists(path.join(workspaceRoot, ...ciWorkflowTemplates_1.githubCiWorkflowRelativePath.split('/'))),
        pathExists(path.join(archpilotDir, 'baseline', 'architecture-baseline.json')),
        pathExists(path.join(archpilotDir, 'reports', 'architecture-drift.json')),
        pathExists(path.join(archpilotDir, 'reports', 'architecture-review-report.md')),
    ]);
    const contractFileCount = hasContractsFolder ? await countContractFiles(contractsDir) : 0;
    const hasAdrRelatedFindings = (validationStatus?.results ?? []).some((result) => {
        if (result.passed !== false) {
            return false;
        }
        return typeof result === 'object' && result !== null && typeof result.id === 'string'
            ? (result.id.startsWith('AP-ADR-') || result.id === 'AP-SAFE-001')
            : false;
    });
    const requiredAdrScaffolds = await (0, adrScaffoldGeneration_1.buildRequiredAdrScaffoldSuggestions)(workspaceRoot, {
        ...(validationStatus ? { validationStatus } : {}),
    });
    return {
        hasArchitectureConfig,
        governedModuleCount,
        hasDependencyRules,
        hasLayerRules,
        hasContractsFolder,
        contractFileCount,
        hasGithubCiWorkflow,
        hasBaselineSnapshot: options?.hasBaselineSnapshot ?? detectedBaselineSnapshot,
        hasDriftReport: options?.hasDriftReport ?? detectedDriftReport,
        hasCloudConnection: options?.hasCloudConnection ?? false,
        hasReviewReport: options?.hasReviewReport ?? detectedReviewReport,
        hasAdrRelatedFindings,
        requiredAdrScaffoldCount: requiredAdrScaffolds.length,
        ...(validationStatus ? { validationStatus } : {}),
    };
}
function uniqueActions(actions) {
    const seen = new Set();
    const deduped = [];
    for (const action of actions) {
        const key = `${action.command}::${action.inspectorActionId ?? ''}`;
        if (seen.has(key)) {
            continue;
        }
        seen.add(key);
        deduped.push(action);
    }
    return deduped;
}
function buildModelFromSnapshot(snapshot, generatedAtUtc, renderContext) {
    const summary = snapshot.validationStatus?.summary;
    const hasValidationStatus = !!snapshot.validationStatus;
    const firstSuccessfulValidationCompleted = hasValidationStatus;
    const failedResults = snapshot.validationStatus?.results?.filter((result) => !result.passed) ?? [];
    const hasFailedFindings = failedResults.length > 0;
    const setupGapCountFromStatus = summary?.setupGaps;
    const hasMissingDependencyRules = !snapshot.hasDependencyRules;
    const hasMissingLayerRules = !snapshot.hasLayerRules;
    const hasMissingContracts = snapshot.contractFileCount === 0;
    const hasGovernedModules = snapshot.governedModuleCount > 0;
    const hasMissingInitialSetupArtifacts = hasMissingDependencyRules || hasMissingLayerRules || (hasGovernedModules && hasMissingContracts);
    const missingGithubCiWorkflow = firstSuccessfulValidationCompleted && !snapshot.hasGithubCiWorkflow;
    const missingAdrScaffolds = firstSuccessfulValidationCompleted &&
        snapshot.hasAdrRelatedFindings &&
        snapshot.requiredAdrScaffoldCount > 0;
    const setupGapCountFromFiles = (hasMissingDependencyRules ? 1 : 0) +
        (hasMissingLayerRules ? 1 : 0) +
        (hasGovernedModules && hasMissingContracts ? 1 : 0);
    const setupGapCount = typeof setupGapCountFromStatus === 'number'
        ? ensureScore(setupGapCountFromStatus, 0, 1000)
        : setupGapCountFromFiles;
    const readinessScore = typeof summary?.readinessScore === 'number'
        ? ensureScore(summary.readinessScore)
        : snapshot.hasArchitectureConfig
            ? ensureScore(100 - setupGapCountFromFiles * 20)
            : 0;
    const architectureHealthScore = typeof summary?.healthScore === 'number' ? ensureScore(summary.healthScore) : undefined;
    const errors = ensureScore(summary?.errors ?? 0, 0, 100000);
    const warnings = ensureScore(summary?.warnings ?? 0, 0, 100000);
    const info = ensureScore(summary?.info ?? 0, 0, 100000);
    const cleanValidation = firstSuccessfulValidationCompleted && !hasFailedFindings && setupGapCount === 0;
    const onboardingState = snapshot.hasArchitectureConfig && firstSuccessfulValidationCompleted && setupGapCount === 0
        ? 'setup-complete'
        : 'setup-incomplete';
    const checklistItems = [
        {
            id: 'initialized',
            label: 'Architecture initialized',
            completed: snapshot.hasArchitectureConfig,
            description: '.archpilot/architecture.json exists.',
        },
        {
            id: 'validated',
            label: 'Validation has run at least once',
            completed: firstSuccessfulValidationCompleted,
            description: 'Validation status is available for setup/readiness guidance.',
        },
        {
            id: 'dependency-rules',
            label: 'Dependency rules config present',
            completed: snapshot.hasDependencyRules,
            description: '.archpilot/dependency-rules.json',
        },
        {
            id: 'layer-rules',
            label: 'Layer rules config present',
            completed: snapshot.hasLayerRules,
            description: '.archpilot/layer-rules.json',
        },
        {
            id: 'contracts',
            label: 'Module contracts generated',
            completed: !hasGovernedModules || snapshot.contractFileCount > 0,
            description: !hasGovernedModules
                ? 'No governed modules configured.'
                : snapshot.contractFileCount > 0
                    ? `${snapshot.contractFileCount} contract file(s) found.`
                    : 'No .archpilot/contracts/*.contract.json files found.',
        },
        {
            id: 'github-ci-governance',
            label: 'GitHub CI governance workflow present',
            completed: snapshot.hasGithubCiWorkflow,
            description: snapshot.hasGithubCiWorkflow
                ? `${ciWorkflowTemplates_1.githubCiWorkflowRelativePath} exists.`
                : `${ciWorkflowTemplates_1.githubCiWorkflowRelativePath} is missing.`,
        },
    ];
    const setupGithubCiAction = {
        label: 'Setup GitHub CI',
        command: 'ArchPilot: Setup GitHub CI Validation + Upload',
        inspectorActionId: 'setup-github-ci-governance',
        description: 'Run ArchPilot validation on pull requests and validation plus governance upload on main.',
    };
    const generateAdrScaffoldsAction = {
        label: 'Generate ADR Scaffolds',
        command: 'ArchPilot: Generate Required ADR Scaffolds',
        inspectorActionId: 'generate-required-adr-scaffolds',
        description: 'Create ADR templates for missing architecture decisions based on current validation findings.',
    };
    const runValidationAction = {
        label: 'Run Validation',
        command: 'archpilot validate',
        inspectorActionId: 'run-validation',
        runValidation: true,
        description: 'Validate the current architecture and refresh findings, drift inputs, and governance artifacts.',
    };
    const reviewFindingsAction = {
        label: 'Review Findings',
        command: 'Open Findings tab',
        inspectorTab: 'findings',
        description: 'Open Findings to review architecture validation issues and structural problems.',
    };
    const reviewDriftAction = {
        label: 'Review Drift',
        command: 'Open Drift tab',
        inspectorTab: 'drift',
        description: 'Open Drift to compare the current architecture against a saved baseline.',
    };
    const createBaselineAction = {
        label: 'Create Drift Baseline',
        command: 'Create baseline from current architecture',
        driftWorkflowAction: 'create-baseline',
        description: 'Save the current architecture as the reference snapshot for future drift checks.',
    };
    const runDriftCheckAction = {
        label: 'Run Drift Check',
        command: 'Run drift check against baseline',
        driftWorkflowAction: 'run-check',
        description: 'Compare the current architecture against the saved baseline snapshot.',
    };
    const manageCloudAction = {
        label: 'Manage Cloud Connection',
        command: 'ArchPilot: Manage Cloud Connection',
        inspectorActionId: 'manage-cloud-config',
        description: 'Save or update the ArchPilot Cloud API token and upload preference for this repository.',
    };
    const uploadGovernanceAction = {
        label: 'Upload Governance Snapshot Now',
        command: 'ArchPilot: Upload Governance Snapshot Now',
        inspectorActionId: 'upload-governance-snapshot',
        description: 'Upload the latest validated governance snapshot to ArchPilot Cloud.',
    };
    const manageExceptionsAction = {
        label: 'Create Exceptions',
        command: 'ArchPilot: Manage Exceptions',
        inspectorActionId: 'manage-exceptions',
        description: 'Record approved architecture exceptions for acceptable temporary violations.',
    };
    const generateReviewReportAction = {
        label: 'Generate Architecture Review Report',
        command: 'ArchPilot: Generate Review Report',
        inspectorActionId: 'generate-architecture-review-report',
        description: 'Generate a current architecture review report for sharing and governance review.',
    };
    const stages = [];
    let stagedStepCount = 0;
    const pushStage = (stage) => {
        if (stage.steps.length > 0 && stages.length < 4 && stagedStepCount < 6) {
            const availableSlots = Math.max(0, 6 - stagedStepCount);
            const maxStageSteps = stages.length === 0 ? Math.min(4, availableSlots) : Math.min(2, availableSlots);
            const trimmedSteps = stage.steps
                .map((step, index) => ({ step, index }))
                .sort((left, right) => {
                const priorityCompare = (left.step.priority ?? left.index) - (right.step.priority ?? right.index);
                if (priorityCompare !== 0) {
                    return priorityCompare;
                }
                return left.index - right.index;
            })
                .slice(0, maxStageSteps)
                .sort((left, right) => left.index - right.index)
                .map((entry) => entry.step);
            if (trimmedSteps.length === 0) {
                return;
            }
            stages.push({
                ...stage,
                steps: trimmedSteps,
            });
            stagedStepCount += trimmedSteps.length;
        }
    };
    if (!snapshot.hasArchitectureConfig) {
        pushStage({
            id: 'setup',
            title: 'Setup',
            description: 'Initialize ArchPilot before validation and governance workflows can guide this repository.',
            steps: [
                {
                    id: 'smart-init',
                    title: 'Run Smart Init',
                    description: 'Detect a deterministic starting architecture proposal for this repository.',
                    priority: 1,
                    action: {
                        label: 'Run Smart Init',
                        command: 'archpilot smart-init-proposal',
                        description: 'Run ArchPilot Smart Init and review the proposed architecture setup.',
                    },
                },
                {
                    id: 'review-generated-config',
                    title: 'Review generated architecture.json',
                    description: 'Confirm project shape, module boundaries, and governance defaults before applying them.',
                    priority: 2,
                },
                {
                    id: 'define-modules-contracts',
                    title: 'Define modules and contracts',
                    description: 'Lock in clear architecture boundaries and contract expectations before validation starts.',
                    priority: 3,
                },
            ],
        });
    }
    else if (!firstSuccessfulValidationCompleted) {
        pushStage({
            id: hasGovernedModules && hasMissingInitialSetupArtifacts ? 'setup' : 'validate',
            title: hasGovernedModules && hasMissingInitialSetupArtifacts ? 'Setup' : 'Validate',
            description: hasGovernedModules && hasMissingInitialSetupArtifacts
                ? 'Generate missing setup artifacts before the first validation pass.'
                : 'Run the first validation pass to establish findings, readiness, and architecture health.',
            steps: [
                ...(hasGovernedModules && hasMissingInitialSetupArtifacts
                    ? [
                        {
                            id: 'generate-missing-config-contracts',
                            title: 'Generate Missing Config & Contracts',
                            description: 'Create dependency/layer config and module contracts before first validation.',
                            priority: 1,
                            action: {
                                label: 'Generate Missing Config & Contracts',
                                command: 'archpilot bootstrap --with-contracts',
                                inspectorActionId: 'bootstrap-config-and-contracts',
                                description: 'Create missing setup config and module contracts in one deterministic pass.',
                            },
                        },
                        {
                            id: 'run-validation',
                            title: 'Run Architecture Validation',
                            description: 'Validate after setup artifacts exist to reduce first-run setup noise.',
                            priority: 2,
                            action: runValidationAction,
                        },
                    ]
                    : [
                        {
                            id: 'run-validation',
                            title: 'Run Architecture Validation',
                            description: 'Validate the current architecture and generate findings for the Inspector.',
                            priority: 1,
                            action: runValidationAction,
                        },
                    ]),
                {
                    id: 'review-findings',
                    title: 'Review Findings',
                    description: 'Use Findings to inspect architecture violations, policy issues, and structural problems.',
                    priority: hasGovernedModules && hasMissingInitialSetupArtifacts ? 3 : 2,
                    action: reviewFindingsAction,
                },
                {
                    id: 'fix-structural-issues',
                    title: 'Fix structural issues',
                    description: 'Address the most important module boundary and dependency problems first.',
                    priority: hasGovernedModules && hasMissingInitialSetupArtifacts ? 4 : 3,
                },
            ],
        });
    }
    else if (hasFailedFindings) {
        pushStage({
            id: 'validate',
            title: 'Validate',
            description: 'Use the latest findings to drive the next architecture fixes instead of broad generic cleanup.',
            steps: [
                {
                    id: 'review-current-findings',
                    title: 'Review Findings',
                    description: 'Inspect the current architecture findings and identify the highest-impact fixes.',
                    priority: 1,
                    action: reviewFindingsAction,
                },
                {
                    id: 'fix-high-severity',
                    title: 'Fix high-severity issues',
                    description: 'Resolve error-level findings first to improve architecture health and reduce risk.',
                    priority: 2,
                },
                {
                    id: 'exceptions',
                    title: 'Create Exceptions for acceptable violations',
                    description: 'Record approved exceptions only for findings that are intentionally temporary or acceptable.',
                    priority: 3,
                    action: manageExceptionsAction,
                },
                {
                    id: 'rerun-validation',
                    title: 'Re-run validation',
                    description: 'Refresh findings after fixes or exception updates.',
                    priority: 4,
                    action: runValidationAction,
                },
            ],
        });
    }
    if (snapshot.hasArchitectureConfig && firstSuccessfulValidationCompleted && !snapshot.hasBaselineSnapshot) {
        pushStage({
            id: 'stabilize',
            title: 'Stabilize',
            description: 'Capture a baseline so drift becomes an explicit part of the architecture workflow.',
            steps: [
                {
                    id: 'create-baseline',
                    title: 'Create Drift Baseline',
                    description: 'Save the current architecture as the reference point for future drift checks.',
                    action: createBaselineAction,
                },
                {
                    id: 'commit-baseline',
                    title: 'Commit baseline snapshot',
                    description: 'Commit the generated baseline artifact so future comparisons use a stable reference.',
                },
            ],
        });
    }
    else if (snapshot.hasBaselineSnapshot && !snapshot.hasDriftReport) {
        pushStage({
            id: 'stabilize',
            title: 'Stabilize',
            description: 'Use drift checks to compare the current architecture against the saved baseline.',
            steps: [
                {
                    id: 'run-drift-check',
                    title: 'Run Drift Check',
                    description: 'Compare the current architecture against the baseline snapshot.',
                    action: runDriftCheckAction,
                },
                {
                    id: 'review-drift-changes',
                    title: 'Review Drift Changes',
                    description: 'Inspect module and dependency changes surfaced by the drift workflow.',
                    action: reviewDriftAction,
                },
            ],
        });
    }
    if (firstSuccessfulValidationCompleted && hasFailedFindings) {
        pushStage({
            id: 'govern',
            title: 'Govern',
            description: 'Use findings to drive governance workflows once the current architecture state is understood.',
            steps: snapshot.hasCloudConnection
                ? [
                    {
                        id: 'upload-findings',
                        title: 'Upload Governance Snapshot to ArchPilot Cloud',
                        description: 'Send the latest validated governance snapshot to ArchPilot Cloud for policy and compliance review.',
                        action: uploadGovernanceAction,
                    },
                    {
                        id: 'review-governance',
                        title: 'Review governance policies',
                        description: 'Check how findings align with policy enforcement and governance expectations.',
                        action: {
                            label: 'Configure Policy Enforcement',
                            command: 'ArchPilot: Configure Policy Enforcement',
                            inspectorActionId: 'create-policy-file',
                            description: 'Review or create local policy enforcement settings.',
                        },
                    },
                ]
                : [
                    {
                        id: 'configure-cloud',
                        title: 'Connect ArchPilot Cloud',
                        description: 'Save the repository Cloud connection before uploading findings and governance snapshots.',
                        action: manageCloudAction,
                    },
                    {
                        id: 'track-compliance',
                        title: 'Track architecture compliance',
                        description: 'Once Cloud is configured, upload governance snapshots to track compliance over time.',
                    },
                ],
        });
    }
    if (cleanValidation) {
        pushStage({
            id: 'maintain',
            title: 'Maintain',
            description: 'With setup, validation, and findings in a healthy state, move into repeatable governance workflows.',
            steps: [
                {
                    id: 'review-report',
                    title: 'Generate Architecture Review Report',
                    description: snapshot.hasReviewReport
                        ? 'Refresh the architecture review report with the latest healthy validation state.'
                        : 'Generate a shareable architecture review report for the current repository state.',
                    action: generateReviewReportAction,
                },
                {
                    id: 'ci-validation',
                    title: 'Set up CI validation',
                    description: 'Keep architecture checks running automatically in pull requests and on the main branch.',
                    action: setupGithubCiAction,
                },
                {
                    id: 'governance-collaboration',
                    title: 'Configure governance and team workflows',
                    description: 'Connect Cloud, review policies, and share reports so the team can track architecture health together.',
                    action: snapshot.hasCloudConnection ? uploadGovernanceAction : manageCloudAction,
                },
            ],
        });
    }
    if (stages.length === 0) {
        pushStage({
            id: 'maintain',
            title: 'Maintain',
            description: 'Keep the architecture workflow active with periodic validation and report refreshes.',
            steps: [
                {
                    id: 'rerun-validation-maintenance',
                    title: 'Re-run validation',
                    description: 'Refresh findings after changes to keep the architecture picture current.',
                    action: runValidationAction,
                },
                {
                    id: 'review-drift-maintenance',
                    title: 'Review drift and history',
                    description: 'Use Drift and History together to understand how architecture changes over time.',
                    action: reviewDriftAction,
                },
            ],
        });
    }
    const recommendedPrimaryActionBase = !snapshot.hasArchitectureConfig
        ? {
            label: 'Run Smart Init',
            command: 'archpilot smart-init-proposal',
            description: 'Detect and review a deterministic architecture proposal for this repository.',
        }
        : !firstSuccessfulValidationCompleted && hasGovernedModules && hasMissingInitialSetupArtifacts
            ? {
                label: 'Generate Missing Config & Contracts',
                command: 'archpilot bootstrap --with-contracts',
                inspectorActionId: 'bootstrap-config-and-contracts',
                description: 'Create missing setup config and module contracts before the first validation run.',
            }
            : !firstSuccessfulValidationCompleted
                ? runValidationAction
                : setupGapCount > 0
                    ? hasMissingDependencyRules || hasMissingLayerRules
                        ? {
                            label: 'Bootstrap Missing Config',
                            command: 'archpilot bootstrap --with-contracts',
                            inspectorActionId: 'bootstrap-config-and-contracts',
                            description: 'Create missing setup config and contracts in one deterministic pass.',
                        }
                        : hasGovernedModules && hasMissingContracts
                            ? {
                                label: 'Generate Contracts',
                                command: 'archpilot contracts generate',
                                inspectorActionId: 'generate-module-contracts',
                                description: 'Generate missing module contracts for discovered modules.',
                            }
                            : runValidationAction
                    : hasFailedFindings
                        ? reviewFindingsAction
                        : !snapshot.hasBaselineSnapshot
                            ? createBaselineAction
                            : snapshot.hasBaselineSnapshot && !snapshot.hasDriftReport
                                ? runDriftCheckAction
                                : missingAdrScaffolds
                                    ? generateAdrScaffoldsAction
                                    : missingGithubCiWorkflow
                                        ? {
                                            label: 'Set up GitHub CI validation + upload',
                                            command: 'ArchPilot: Setup GitHub CI Validation + Upload',
                                            inspectorActionId: 'setup-github-ci-governance',
                                            description: 'Run ArchPilot validation on pull requests and validation plus governance upload on main.',
                                        }
                                        : {
                                            label: 'Publish Badge',
                                            command: 'archpilot badges publish',
                                            inspectorActionId: 'publish-badges',
                                            description: 'Publish the latest ArchPilot Score badge for repository visibility.',
                                        };
    const recommendedCommandsBase = uniqueActions(onboardingState === 'setup-incomplete'
        ? [
            recommendedPrimaryActionBase,
            runValidationAction,
            {
                label: 'Bootstrap Missing Config',
                command: 'archpilot bootstrap --with-contracts',
                inspectorActionId: 'bootstrap-config-and-contracts',
                description: 'Generate missing setup config and contracts.',
            },
            {
                label: 'Generate Contracts',
                command: 'archpilot contracts generate',
                inspectorActionId: 'generate-module-contracts',
                description: 'Create missing module contracts from discovered modules.',
            },
            {
                label: 'Review Findings',
                command: 'Open Findings tab',
                inspectorTab: 'findings',
                description: 'Inspect current findings before choosing follow-up fixes or governance steps.',
            },
            createBaselineAction,
            runDriftCheckAction,
            ...(missingAdrScaffolds ? [generateAdrScaffoldsAction] : []),
            ...(snapshot.hasCloudConnection ? [uploadGovernanceAction] : [manageCloudAction]),
            ...(missingGithubCiWorkflow ? [setupGithubCiAction] : []),
        ]
        : [
            recommendedPrimaryActionBase,
            reviewFindingsAction,
            reviewDriftAction,
            ...(missingAdrScaffolds ? [generateAdrScaffoldsAction] : []),
            ...(snapshot.hasCloudConnection ? [uploadGovernanceAction] : [manageCloudAction]),
            ...(missingGithubCiWorkflow ? [setupGithubCiAction] : []),
            {
                label: 'Run CI Validation',
                command: 'archpilot validate --ci',
                description: 'Use CI mode to enforce architecture health in pipelines.',
            },
            {
                label: 'Publish Badge',
                command: 'archpilot badges publish',
                inspectorActionId: 'publish-badges',
                description: 'Refresh the ArchPilot Score badge for README and visibility.',
            },
            {
                label: 'Open Inspector',
                command: 'ArchPilot: Open Architecture Inspector',
                inspectorActionId: 'refresh-inspector',
                description: 'Explore architecture map, drift, findings, and trends.',
            },
        ]);
    const recommendedCommands = recommendedCommandsBase
        .filter((action) => renderContext === 'inspector'
        ? action.command !== 'ArchPilot: Open Architecture Inspector'
        : true)
        .slice(0, onboardingState === 'setup-incomplete' ? 5 : 4);
    const recommendedPrimaryAction = recommendedCommands.find((action) => action.command === recommendedPrimaryActionBase.command) ??
        recommendedPrimaryActionBase;
    const summaryItems = onboardingState === 'setup-incomplete'
        ? [
            !snapshot.hasArchitectureConfig
                ? 'No architecture.json is present yet.'
                : firstSuccessfulValidationCompleted
                    ? `Readiness ${readinessScore}/100 with ${setupGapCount} setup gap(s).`
                    : 'Architecture config exists, but validation has not run yet.',
            ...(hasFailedFindings
                ? [`Current findings: ${errors} error(s), ${warnings} warning(s), ${info} info.`]
                : []),
            ...(!snapshot.hasBaselineSnapshot
                ? ['No drift baseline exists yet.']
                : snapshot.hasBaselineSnapshot && !snapshot.hasDriftReport
                    ? ['Baseline exists, but drift has not been checked yet.']
                    : []),
            ...(snapshot.hasCloudConnection
                ? hasFailedFindings
                    ? ['ArchPilot Cloud is configured and ready for governance snapshot uploads.']
                    : []
                : ['ArchPilot Cloud is not configured yet.']),
            ...(missingAdrScaffolds ? ['Required ADR scaffolds are still missing for current architecture findings.'] : []),
            ...(missingGithubCiWorkflow ? ['GitHub CI governance is not configured yet.'] : []),
            ...(architectureHealthScore !== undefined
                ? [`Architecture health score is ${architectureHealthScore}/100.`]
                : []),
        ]
        : [
            `Readiness ${readinessScore}/100 with no setup gaps.`,
            ...(missingAdrScaffolds ? ['Required ADR scaffolds are still missing for current architecture findings.'] : []),
            ...(missingGithubCiWorkflow ? ['GitHub CI governance is not configured yet.'] : []),
            ...(!snapshot.hasBaselineSnapshot
                ? ['No drift baseline exists yet.']
                : snapshot.hasBaselineSnapshot && !snapshot.hasDriftReport
                    ? ['Baseline exists, but drift has not been checked yet.']
                    : []),
            ...(architectureHealthScore !== undefined
                ? [`Architecture health score is ${architectureHealthScore}/100.`]
                : []),
            hasFailedFindings
                ? 'Setup is healthy; focus on remaining findings.'
                : 'Setup is healthy; continue normal operating workflows.',
        ];
    const fastestPathToGreen = onboardingState === 'setup-incomplete'
        ? [
            'Run validation to classify current setup gaps and quality findings.',
            'Apply deterministic safe fixes when available.',
            'Bootstrap missing setup artifacts and contracts.',
            ...(missingAdrScaffolds
                ? ['Generate ADR scaffolds for missing architecture decisions before finalizing governance documentation.']
                : []),
            ...(missingGithubCiWorkflow
                ? ['Set up GitHub CI validation + upload so pull requests run `archpilot validate --ci` and main runs validation plus `archpilot governance upload`.']
                : []),
            'Re-run validation until setup gaps reach zero.',
        ]
        : [
            ...(missingAdrScaffolds
                ? ['Generate ADR scaffolds for missing architecture decisions before finalizing governance documentation.']
                : []),
            ...(missingGithubCiWorkflow
                ? ['Set up GitHub CI validation + upload so pull requests run `archpilot validate --ci` and main runs validation plus `archpilot governance upload`.']
                : []),
            'Keep validation running in CI (`archpilot validate --ci`).',
            'Use Inspector for drift/findings exploration.',
            'Track architecture score trends over time.',
        ];
    return {
        version: 1,
        generatedAtUtc,
        onboardingState,
        autoFocusNextSteps: onboardingState === 'setup-incomplete',
        ...(architectureHealthScore !== undefined ? { architectureHealthScore } : {}),
        setupReadinessScore: readinessScore,
        setupGapCount,
        firstSuccessfulValidationCompleted,
        statusMessage: onboardingState === 'setup-incomplete'
            ? firstSuccessfulValidationCompleted
                ? 'Setup incomplete'
                : 'Onboarding in progress'
            : 'Onboarding complete',
        summaryItems,
        recommendedPrimaryAction,
        recommendedCommands,
        workflowHeading: onboardingState === 'setup-incomplete'
            ? 'Fastest Path To Green'
            : 'Next Recommended Workflows',
        fastestPathToGreen,
        checklistItems,
        stages,
    };
}
async function buildSetupNextStepsModel(input) {
    const validationStatus = input.validationStatus ?? (await readValidationStatusFromWorkspace(input.workspaceRoot));
    const snapshot = await buildSetupSnapshot(input.workspaceRoot, validationStatus, {
        ...(typeof input.hasCloudConnection === 'boolean'
            ? { hasCloudConnection: input.hasCloudConnection }
            : {}),
        ...(typeof input.hasBaselineSnapshot === 'boolean'
            ? { hasBaselineSnapshot: input.hasBaselineSnapshot }
            : {}),
        ...(typeof input.hasDriftReport === 'boolean'
            ? { hasDriftReport: input.hasDriftReport }
            : {}),
        ...(typeof input.hasReviewReport === 'boolean'
            ? { hasReviewReport: input.hasReviewReport }
            : {}),
    });
    return buildModelFromSnapshot(snapshot, input.generatedAtUtc ?? new Date().toISOString(), input.renderContext ?? 'report');
}
function renderSetupNextStepsMarkdown(model) {
    const lines = [];
    lines.push('<!-- archpilot:managed generated-by=setup-refresh -->');
    lines.push('# ArchPilot Setup Next Steps');
    lines.push('');
    lines.push(`- Generated at: ${model.generatedAtUtc}`);
    lines.push(`- Onboarding state: ${model.onboardingState}`);
    lines.push(`- Setup Readiness Score: ${model.setupReadinessScore} / 100`);
    lines.push(`- Setup Gaps: ${model.setupGapCount}`);
    if (typeof model.architectureHealthScore === 'number') {
        lines.push(`- Architecture Health Score: ${model.architectureHealthScore} / 100`);
    }
    lines.push(`- First successful validation completed: ${model.firstSuccessfulValidationCompleted ? 'yes' : 'no'}`);
    lines.push('');
    lines.push('## Status');
    lines.push(model.statusMessage);
    lines.push('');
    lines.push('## Summary');
    for (const item of model.summaryItems) {
        lines.push(`- ${item}`);
    }
    lines.push('');
    lines.push('## Recommended Primary Action');
    lines.push(`- ${model.recommendedPrimaryAction.label}: \`${model.recommendedPrimaryAction.command}\``);
    if (model.recommendedPrimaryAction.description) {
        lines.push(`- Why: ${model.recommendedPrimaryAction.description}`);
    }
    lines.push('');
    lines.push(`## ${model.workflowHeading}`);
    for (const step of model.fastestPathToGreen) {
        lines.push(`- ${step}`);
    }
    lines.push('');
    lines.push('## Useful Commands');
    for (const action of model.recommendedCommands) {
        const description = action.description ? ` - ${action.description}` : '';
        lines.push(`- \`${action.command}\`${description}`);
    }
    lines.push('');
    lines.push('## Setup Checklist');
    for (const item of model.checklistItems) {
        lines.push(`- [${item.completed ? 'x' : ' '}] ${item.label}`);
        if (item.description) {
            lines.push(`  - ${item.description}`);
        }
    }
    lines.push('');
    return `${lines.join('\n')}\n`;
}
function renderSetupNextStepsConsole(model) {
    const lines = [];
    lines.push('Suggested Next Steps');
    lines.push(`State: ${model.onboardingState}`);
    lines.push(`Readiness: ${model.setupReadinessScore} / 100`);
    lines.push(`Setup gaps: ${model.setupGapCount}`);
    lines.push('');
    lines.push(`1. ${model.recommendedPrimaryAction.label}: \`${model.recommendedPrimaryAction.command}\``);
    const remaining = model.recommendedCommands
        .filter((action) => action.command !== model.recommendedPrimaryAction.command)
        .slice(0, 3);
    for (const [index, action] of remaining.entries()) {
        lines.push(`${index + 2}. ${action.label}: \`${action.command}\``);
    }
    return `${lines.join('\n')}\n`;
}
async function writeSetupNextStepsReport(workspaceRoot, model) {
    const reportPath = path.join(workspaceRoot, exports.setupNextStepsReportRelativePath);
    await node_fs_1.promises.mkdir(path.dirname(reportPath), { recursive: true });
    await node_fs_1.promises.writeFile(reportPath, renderSetupNextStepsMarkdown(model), { encoding: 'utf8' });
    return reportPath;
}
async function refreshSetupNextStepsForWorkspace(input) {
    const model = await buildSetupNextStepsModel({
        workspaceRoot: input.workspaceRoot,
        ...(input.validationStatus ? { validationStatus: input.validationStatus } : {}),
        ...(input.generatedAtUtc ? { generatedAtUtc: input.generatedAtUtc } : {}),
    });
    await writeSetupNextStepsReport(input.workspaceRoot, model);
    return model;
}
//# sourceMappingURL=setupNextSteps.js.map