"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMetadataCommandWriteSummary = createMetadataCommandWriteSummary;
exports.createMetadataReportingAlignment = createMetadataReportingAlignment;
exports.renderMetadataOperationText = renderMetadataOperationText;
exports.createMetadataRejectionEvidence = createMetadataRejectionEvidence;
exports.detectMetadataFamilyForReporting = detectMetadataFamilyForReporting;
const command_write_summary_1 = require("../../../lib/license/command-write-summary");
const output_1 = require("../../../lib/output");
const update_application_1 = require("./update-application");
function createMetadataCommandWriteSummary(options) {
    return (0, command_write_summary_1.normalizeCommandWriteSummary)({
        commandFamily: "metadata_update",
        jsonOnly: options.jsonOnly,
        primaryOutputArtifacts: [options.artifactPath],
        updatedArtifacts: [
            {
                path: options.artifactPath,
                action: options.writeApplied ? "changed" : options.writeRequested ? "kept" : "inspected",
                reason: options.writeApplied
                    ? undefined
                    : options.writeRequested
                        ? "no_write"
                        : "read_only_output",
                materialUpdate: options.writeApplied ? true : false
            }
        ]
    });
}
function createMetadataReportingAlignment(options) {
    return {
        surfaceMode: options.writeRequested ? "write-attempt" : "read-only",
        family: options.family,
        findingsTaxonomy: "shared-findings",
        noWrite: !options.writeRequested,
        evidenceLanes: getMetadataEvidenceLanes(options.family),
        adjacentEvidencePolicy: "visible-not-authority"
    };
}
function getMetadataEvidenceLanes(family) {
    switch (family) {
        case "prompt":
            return [
                "promptMarkdown.promptVersion",
                "promptMarkdown.layer",
                "promptMarkdown.action",
                "promptManifest.promptManifestVersion",
                "promptManifest.promptVersion",
                "promptManifest.entryVersion"
            ];
        case "prompt-manifest":
            return [
                "promptManifest.promptManifestVersion",
                "promptManifest.promptVersion",
                "promptManifest.entryVersion",
                "promptManifest.entryLayer",
                "promptManifest.entryAction"
            ];
        case "template":
            return [
                "templateMarkdown.frontMatter",
                "templateFamily.adjacentManifestEvidence"
            ];
        case "template-manifest":
            return [
                "templateManifest.templateManifestVersion",
                "templateManifest.templateVersion",
                "templateManifest.entryVersion",
                "templateManifest.entryDestinationEligibility"
            ];
        case "planning-artifact":
            return [
                "planningArtifact.lifecycleStatus",
                "planningArtifact.familySpecificStatus",
                "planningArtifact.traceability"
            ];
        case "spec-registry":
            return [
                "specRegistry.entryIdentity",
                "specRegistry.sourceMetadata",
                "specRegistry.destination"
            ];
        default:
            return assertUnreachable(family);
    }
}
function renderMetadataOperationText(result, writeRequested) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Metadata Update", "title"),
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                {
                    label: "Result",
                    value: writeRequested
                        ? (result.writeApplied ? "metadata update applied" : "metadata update accepted with no file changes")
                        : "validation completed with no writes"
                },
                { label: "Changed", value: result.changed ? "yes" : "no" },
                { label: "Write requested", value: writeRequested ? "yes" : "no" }
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Artifact",
            fields: [
                { label: "Path", value: result.artifactPath },
                { label: "Family", value: result.family },
                { label: "Reporting surface", value: result.reportingAlignment.surfaceMode },
                { label: "Findings taxonomy", value: result.reportingAlignment.findingsTaxonomy },
                { label: "Adjacent evidence policy", value: result.reportingAlignment.adjacentEvidencePolicy }
            ]
        }),
        "",
        (0, output_1.renderTerminalCompactList)({
            heading: "Field Changes",
            entries: result.fieldChanges.map((fieldChange) => ({
                label: fieldChange.key,
                fields: [{ label: "Intended value", value: fieldChange.value }]
            })),
            emptyMessage: "No field changes were requested."
        }),
        "",
        (0, output_1.renderTerminalCompactList)({
            heading: "Evidence Lanes",
            entries: result.reportingAlignment.evidenceLanes.map((lane) => ({ label: lane })),
            emptyMessage: "No evidence lanes are available for this family."
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Write Boundary",
            lines: [
                writeRequested
                    ? result.writeApplied
                        ? (0, output_1.renderTerminalBoundary)({
                            kind: "write-applied",
                            target: result.artifactPath,
                            targetLabel: "Write target"
                        })
                        : (0, output_1.renderTerminalBoundary)({
                            kind: "mutating-no-op",
                            reason: "Artifact already matched the intended metadata state.",
                            target: result.artifactPath,
                            targetLabel: "Write target"
                        })
                    : (0, output_1.renderTerminalBoundary)({ kind: "read-only" })
            ]
        })
    ];
    if (result.promptVersionEvidence !== undefined) {
        lines.push("", (0, output_1.renderTerminalSection)({
            heading: "Prompt Version Evidence",
            fields: [
                { label: "Prompt Markdown version", value: renderEvidenceValue(result.promptVersionEvidence.promptMarkdown.promptVersion) },
                { label: "Prompt manifest version", value: renderEvidenceValue(result.promptVersionEvidence.promptManifest.promptManifestVersion) },
                { label: "Prompt manifest baseline prompt_version", value: renderEvidenceValue(result.promptVersionEvidence.promptManifest.promptVersion) },
                {
                    label: `Prompt manifest entry version (${result.promptVersionEvidence.promptManifest.entryPath})`,
                    value: renderEvidenceValue(result.promptVersionEvidence.promptManifest.entryVersion)
                }
            ]
        }));
        if (result.promptVersionEvidence.promptManifest.warning !== null) {
            lines.push("", (0, output_1.renderTerminalSection)({
                heading: "Warnings",
                lines: [result.promptVersionEvidence.promptManifest.warning]
            }));
        }
    }
    return lines.join("\n");
}
function renderEvidenceValue(value) {
    return value === null ? "(missing)" : String(value);
}
function createMetadataRejectionEvidence(options) {
    const requestedFields = options.assignments.map((assignment) => assignment.key);
    const rejectedField = requestedFields.find((field) => options.rejectionDetail.includes(`'${field}'`) ||
        options.rejectionDetail.includes(`field ${field}`));
    return {
        commandName: options.commandName,
        artifactPath: options.artifactPath,
        family: options.family,
        requestedFields,
        rejectedField: rejectedField ?? null,
        rejectionReason: options.rejectionDetail,
        writeApplied: false,
        noWriteRequired: true,
        recommendedCommand: buildMetadataRejectionRecoveryCommand({
            commandName: options.commandName,
            artifactPath: options.artifactPath,
            family: options.family,
            rejectedField: rejectedField ?? null
        })
    };
}
function buildMetadataRejectionRecoveryCommand(options) {
    if (options.family === "planning-artifact") {
        if (options.rejectedField === "readiness") {
            return `day-shift task readiness-review --task-definition ${options.artifactPath}; then use day-shift task readiness-authorize with revision-bound review evidence`;
        }
        if (options.rejectedField === "implementation_status") {
            const taskDefinitionPath = options.artifactPath.endsWith("/implementation-summary.md")
                ? options.artifactPath.slice(0, -"implementation-summary.md".length) + "task-definition.md"
                : options.artifactPath;
            return [
                "day-shift task implementation-complete",
                `--task-definition ${taskDefinitionPath}`,
                "--attempt-id <current-attempt-id>",
                "--task-revision <current-task-revision>",
                "--completed-by <actor>",
                "--completed-at <ISO-8601-timestamp>",
                "--dry-run"
            ].join(" ");
        }
        if (options.rejectedField === "reconciliation_status") {
            return `day-shift reconciliation update --reconciliation ${options.artifactPath} --field reconciliation_status=<value>`;
        }
        if (options.rejectedField === "status") {
            return `Use day-shift task close or day-shift task cancel for task lifecycle status transitions on ${options.artifactPath}.`;
        }
        if (options.rejectedField === "completed_at") {
            const taskDefinitionPath = options.artifactPath.endsWith("/implementation-summary.md")
                ? options.artifactPath.slice(0, -"implementation-summary.md".length) + "task-definition.md"
                : options.artifactPath;
            return `Use day-shift task close --task-definition ${taskDefinitionPath} with the exact accepted review result.`;
        }
    }
    return "Correct the field family and rerun the matching explicit update or validate-update command.";
}
function detectMetadataFamilyForReporting(artifactPath, content) {
    try {
        return (0, update_application_1.detectMetadataFamily)(artifactPath, content);
    }
    catch {
        return "unsupported";
    }
}
function assertUnreachable(value) {
    throw new TypeError(`Unsupported metadata family '${String(value)}'.`);
}
