"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertArtifactType = assertArtifactType;
exports.parseTaskDefinitionContext = parseTaskDefinitionContext;
exports.parseMilestoneOverviewContext = parseMilestoneOverviewContext;
exports.resolveSummaryMetadataState = resolveSummaryMetadataState;
exports.resolveReconciliationMetadataState = resolveReconciliationMetadataState;
exports.resolveImplementationSummarySectionValues = resolveImplementationSummarySectionValues;
exports.stripImplementationSummaryAuthoringGuidance = stripImplementationSummaryAuthoringGuidance;
exports.hasConcreteImplementationSummaryCoreEvidence = hasConcreteImplementationSummaryCoreEvidence;
exports.stripKnownImplementationSummaryAuthoringGuidance = stripKnownImplementationSummaryAuthoringGuidance;
exports.normalizeCompletedImplementationSummaryNoneStates = normalizeCompletedImplementationSummaryNoneStates;
// Responsibility-focused implementation extracted from the public compatibility facade.
const errors_1 = require("../../errors");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const selector_evidence_1 = require("../reconciliation/selector-evidence");
const semantic_placeholder_1 = require("../semantic-placeholder");
const task_lifecycle_1 = require("../task-lifecycle");
const contracts_1 = require("./contracts");
const document_rendering_1 = require("./document-rendering");
const evidence_1 = require("./evidence");
const template_rendering_1 = require("./template-rendering");
function assertArtifactType(frontMatterLines, filePath, expectedType) {
    const artifactType = (0, selector_evidence_1.readTopLevelField)(frontMatterLines, "artifact_type")?.trim();
    if (artifactType !== expectedType) {
        const guidance = expectedType === "milestone_overview"
            ? [
                "Pass an existing repository-relative --milestone-overview path to a milestone overview artifact.",
                "Do not pass a reconciliation.md path or another planning artifact as the build source."
            ]
            : [];
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' must use artifact_type: ${expectedType}.`, [
            `Found: ${artifactType ?? "(missing)"}`,
            ...guidance
        ]);
    }
}
function parseTaskDefinitionContext(filePath, document, options = {}) {
    const policy = (0, artifact_policy_projection_1.projectArtifactPolicy)([
        "---",
        ...document.frontMatterLines,
        "---"
    ].join("\n"));
    const workflowLevel = policy.workflowLevel ?? "";
    const isCanonicalDirect = workflowLevel === "basic" || workflowLevel === "structured";
    const planningDepth = (0, selector_evidence_1.readTopLevelField)(document.frontMatterLines, "planning_depth")?.trim()
        || (isCanonicalDirect
            ? "standard"
            : (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "planning_depth"));
    const isLightweight = planningDepth === "lightweight";
    const canonicalWorkId = isCanonicalDirect
        ? filePath.match(/^\.day-shift\/planning\/(?:basic|structured)\/([^/]+)\//)?.[1]
            ?? null
        : null;
    if (isLightweight) {
        (0, document_rendering_1.assertLightweightTaskPath)(filePath, document.frontMatterLines);
    }
    return {
        taskDefinitionPath: filePath,
        title: document.title ?? (0, selector_evidence_1.inferTaskTitleFromPath)(filePath),
        slice: isCanonicalDirect
            ? canonicalWorkId
                ?? (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "task")
            : (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "slice"),
        phase: isLightweight || isCanonicalDirect
            ? null
            : (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "phase"),
        milestone: isLightweight || isCanonicalDirect
            ? null
            : (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "milestone"),
        task: (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "task"),
        implementationOrder: workflowLevel === "basic"
            ? (0, selector_evidence_1.readTopLevelField)(document.frontMatterLines, "implementation_order")?.trim() ?? null
            : null,
        planningDepth,
        sliceOverviewPath: workflowLevel === "structured"
            ? (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "work_overview")
            : workflowLevel === "basic"
                ? ""
                : (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "slice_overview"),
        phaseOverviewPath: isLightweight || isCanonicalDirect
            ? null
            : (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "phase_overview"),
        milestoneOverviewPath: isLightweight || isCanonicalDirect
            ? null
            : (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "milestone_overview"),
        upstreamSpecs: (0, selector_evidence_1.parseUpstreamSpecs)(document.frontMatterLines, filePath),
        objectiveText: document.sections.get("Objective") ?? null,
        acceptanceCriteriaText: document.sections.get("Acceptance Criteria") ?? null,
        validationCommandsText: document.sections.get("Validation Commands") ?? null,
        executionMode: policy.evidenceProfile
            ?? (options.allowMissingExecutionMode
                ? ""
                : (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "evidence_profile")),
        workflowLevel,
        agentMode: policy.effectiveAgentMode
    };
}
function parseMilestoneOverviewContext(filePath, document) {
    return {
        milestoneOverviewPath: filePath,
        title: document.title ?? (0, selector_evidence_1.inferTaskTitleFromPath)(filePath),
        slice: (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "slice"),
        phase: (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "phase"),
        milestone: (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "milestone"),
        planningDepth: (0, selector_evidence_1.readRequiredTopLevelField)(document.frontMatterLines, filePath, "planning_depth"),
        sliceOverviewPath: (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "slice_overview"),
        phaseOverviewPath: (0, selector_evidence_1.readRequiredUpstreamField)(document.frontMatterLines, filePath, "phase_overview"),
        upstreamSpecs: (0, selector_evidence_1.parseUpstreamSpecs)(document.frontMatterLines, filePath),
        purposeText: document.sections.get("Purpose") ?? null,
        acceptanceCriteriaText: document.sections.get("Acceptance Criteria") ?? null,
        validationFocusText: document.sections.get("Validation Focus") ?? null
    };
}
function resolveSummaryMetadataState(document, taskDefinitionPath) {
    const lifecycle = document === null
        ? null
        : (0, task_lifecycle_1.projectImplementationSummaryLifecycle)(document.rawText).value;
    const implementationStatus = lifecycle?.currentAttempt?.implementationStatus
        ?? lifecycle?.legacyImplementationStatus
        ?? "pending";
    const reviewDisposition = lifecycle?.currentAttempt?.reviewDisposition
        ?? lifecycle?.legacyReviewDisposition
        ?? null;
    return {
        workflowProvenance: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_provenance")?.trim() || "cli",
        workflowCliCommand: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_cli_command")?.trim()
            || `day-shift implementation-summary build --task-definition ${taskDefinitionPath}`,
        workflowManualException: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_manual_exception")?.trim() || "",
        implementationStatus,
        status: implementationStatus === "completed"
            && (reviewDisposition === "accepted" || reviewDisposition === "accepted_with_follow_up")
            ? "completed"
            : "draft"
    };
}
function resolveReconciliationMetadataState(document, milestoneOverviewPath, taskEvidence) {
    const allDeclaredTasksComplete = taskEvidence !== undefined
        && taskEvidence.completed.length > 0
        && taskEvidence.incomplete.length === 0;
    const existingReconciliationStatus = (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "reconciliation_status")?.trim() || "pending";
    const existingArtifactStatus = (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "status")?.trim() || "draft";
    const alreadyAccepted = existingReconciliationStatus === "completed"
        && existingArtifactStatus === "completed";
    return {
        workflowProvenance: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_provenance")?.trim() || "cli",
        workflowCliCommand: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_cli_command")?.trim()
            || `day-shift reconciliation build --milestone-overview ${milestoneOverviewPath}`,
        workflowManualException: (0, selector_evidence_1.readTopLevelField)(document?.frontMatterLines ?? [], "workflow_manual_exception")?.trim() || "",
        reconciliationStatus: alreadyAccepted
            ? "completed"
            : allDeclaredTasksComplete
                ? "ready_for_review"
                : existingReconciliationStatus === "blocked"
                    ? "blocked"
                    : "pending",
        status: alreadyAccepted
            ? "completed"
            : allDeclaredTasksComplete
                ? "active"
                : existingArtifactStatus === "blocked"
                    ? "blocked"
                    : "draft"
    };
}
function resolveImplementationSummarySectionValues(document, metadata) {
    const defaults = (0, template_rendering_1.getDefaultImplementationSummarySections)();
    for (const [sectionName, defaultValue] of Object.entries(defaults)) {
        const existing = document?.sections.get(sectionName);
        const authoredContent = existing === undefined
            ? ""
            : stripImplementationSummaryAuthoringGuidance(sectionName, existing);
        defaults[sectionName] = authoredContent !== "" ? authoredContent : defaultValue;
    }
    if (metadata.implementationStatus === "completed" && metadata.status === "completed") {
        normalizeCompletedImplementationSummaryNoneStates(defaults);
    }
    return defaults;
}
function stripImplementationSummaryAuthoringGuidance(sectionName, value) {
    const guidance = contracts_1.IMPLEMENTATION_SUMMARY_AUTHORING_GUIDANCE[sectionName];
    if (guidance === undefined) {
        return value;
    }
    let next = value;
    while (next.includes(guidance)) {
        next = next.replace(guidance, "");
    }
    return next.replace(/\n{3,}/g, "\n\n").trim();
}
function hasConcreteImplementationSummaryCoreEvidence(sections) {
    const defaults = (0, template_rendering_1.getDefaultImplementationSummarySections)();
    const coreSections = [
        "Summary",
        "Changed Paths",
        "Acceptance Criteria Results",
        "Validation Performed",
        "Scope Classification",
        "Runtime Evidence Boundary"
    ];
    return coreSections.every((sectionName) => {
        const value = sections[sectionName]?.trim() ?? "";
        if (value === ""
            || value === defaults[sectionName].trim()
            || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(value)) {
            return false;
        }
        if (sectionName !== "Changed Paths") {
            return true;
        }
        return (0, evidence_1.extractSummaryChangedPathEvidence)(value).some((entry) => entry.state === "path");
    });
}
function stripKnownImplementationSummaryAuthoringGuidance(value) {
    let next = value;
    for (const guidance of Object.values(contracts_1.IMPLEMENTATION_SUMMARY_AUTHORING_GUIDANCE)) {
        while (next.includes(guidance)) {
            next = next.replace(guidance, "");
        }
    }
    return next.replace(/\n{3,}/g, "\n\n");
}
function normalizeCompletedImplementationSummaryNoneStates(sections) {
    if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sections.Deviations)) {
        sections.Deviations = "None.";
    }
    if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sections["Risks and Follow-Ups"])) {
        sections["Risks and Follow-Ups"] = "None.";
    }
    if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sections["Open Questions"])) {
        sections["Open Questions"] = "- None currently.";
    }
}
