"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.COMMAND_WRITE_SUMMARY_PLANNING_LAYERS = exports.COMMAND_WRITE_SUMMARY_COMMAND_FAMILIES = void 0;
exports.classifyCommandWriteSummaryArtifact = classifyCommandWriteSummaryArtifact;
exports.normalizeCommandWriteSummaryArtifactUpdate = normalizeCommandWriteSummaryArtifactUpdate;
exports.normalizeCommandWriteSummary = normalizeCommandWriteSummary;
exports.normalizeCommandWriteSummaryOutputMode = normalizeCommandWriteSummaryOutputMode;
exports.shouldEmitHumanReadableCommandOutput = shouldEmitHumanReadableCommandOutput;
exports.classifyReminderEligibilityFromCommandSummary = classifyReminderEligibilityFromCommandSummary;
exports.normalizeCommandWriteSummaryArtifactPaths = normalizeCommandWriteSummaryArtifactPaths;
exports.normalizeCommandWriteSummaryArtifactUpdates = normalizeCommandWriteSummaryArtifactUpdates;
exports.classifyMaterialArtifactUpdate = classifyMaterialArtifactUpdate;
const paths_1 = require("../paths");
exports.COMMAND_WRITE_SUMMARY_COMMAND_FAMILIES = [
    "workspace_init",
    "slice_generation",
    "phase_generation",
    "milestone_generation",
    "task_generation",
    "reconciliation",
    "implementation_summary",
    "metadata_update",
    "validation",
    "doctor",
    "status",
    "unknown",
    "future"
];
exports.COMMAND_WRITE_SUMMARY_PLANNING_LAYERS = [
    "slice",
    "phase",
    "milestone",
    "reconciliation",
    "task",
    "implementation-summary",
    "license-reminder",
    "unknown"
];
const PLANNING_LAYER_SORT_ORDER = new Map(exports.COMMAND_WRITE_SUMMARY_PLANNING_LAYERS.map((layer, index) => [layer, index]));
const MATERIAL_ARTIFACT_REASONS = new Set([
    "accepted_create",
    "accepted_regeneration",
    "accepted_rewrite",
    "accepted_content_change",
    "accepted_refresh",
    "uncertain_coordination_write",
    "provided_material"
]);
const MATERIAL_TASK_PAIR_REASONS = new Set([
    "accepted_create",
    "accepted_regeneration"
]);
const NON_MATERIAL_ARTIFACT_REASONS = new Set([
    "dry_run",
    "json_only",
    "read_only_output",
    "whitespace_only_rewrite",
    "non_semantic_bookkeeping",
    "no_write",
    "non_coordination_artifact",
    "provided_non_material"
]);
const TERMINAL_ALWAYS_ELIGIBLE_COMMAND_FAMILIES = new Set([
    "slice_generation",
    "phase_generation",
    "milestone_generation",
    "task_generation",
    "reconciliation",
    "validation",
    "doctor",
    "status"
]);
const TERMINAL_WRITE_REQUIRED_COMMAND_FAMILIES = new Set([
    "workspace_init",
    "implementation_summary",
    "metadata_update"
]);
const READ_ONLY_TERMINAL_ONLY_COMMAND_FAMILIES = new Set([
    "validation",
    "doctor",
    "status"
]);
const UNKNOWN_OR_FUTURE_COMMAND_FAMILIES = new Set([
    "unknown",
    "future"
]);
function classifyCommandWriteSummaryArtifact(artifactPath) {
    const parsedPath = (0, paths_1.parseRepositoryRelativePath)(artifactPath);
    const pathValue = parsedPath.normalizedPath;
    const segments = parsedPath.segments;
    const fileName = segments[segments.length - 1];
    if (fileName === "LICENSE-REMINDER.md" && isInsidePlanningRoot(segments)) {
        return createClassification(pathValue, "license-reminder", "license-reminder", true);
    }
    if (isSliceOverviewPath(segments)) {
        return createClassification(pathValue, "slice", "slice-overview", true);
    }
    if (isPhaseOverviewPath(segments)) {
        return createClassification(pathValue, "phase", "phase-overview", true);
    }
    if (isMilestoneOverviewPath(segments)) {
        return createClassification(pathValue, "milestone", "milestone-overview", true);
    }
    if (isMilestoneReconciliationPath(segments)) {
        return createClassification(pathValue, "reconciliation", "milestone-reconciliation", true);
    }
    if (isTaskDefinitionPath(segments)) {
        return createClassification(pathValue, "task", "task-definition", false);
    }
    if (isImplementationSummaryPath(segments)) {
        return createClassification(pathValue, "implementation-summary", "implementation-summary", false);
    }
    return createClassification(pathValue, "unknown", "unknown", false);
}
function normalizeCommandWriteSummaryArtifactUpdate(input, options = {
    dryRun: false,
    jsonOnly: false
}) {
    const classification = classifyCommandWriteSummaryArtifact(input.path);
    const layer = input.layer ?? classification.layer;
    const isCoordinationArtifact = input.isCoordinationArtifact ?? classification.isCoordinationArtifact;
    const action = input.action ?? actionFromReason(input.reason) ?? "unknown";
    const reason = input.reason ?? inferArtifactUpdateReason({
        action,
        dryRun: options.dryRun,
        jsonOnly: options.jsonOnly,
        isCoordinationArtifact,
        artifactKind: classification.artifactKind,
        materialUpdate: input.materialUpdate
    });
    return {
        ...classification,
        layer,
        isCoordinationArtifact,
        action,
        reason,
        materialUpdate: classifyMaterialArtifactUpdate(reason, isCoordinationArtifact, classification.artifactKind)
    };
}
function normalizeCommandWriteSummary(options) {
    const dryRun = options.dryRun ?? false;
    const jsonOnly = options.jsonOnly ?? false;
    const updatedArtifacts = normalizeCommandWriteSummaryArtifactUpdates(options.updatedArtifacts ?? [], { dryRun, jsonOnly });
    return {
        commandFamily: options.commandFamily ?? "unknown",
        dryRun,
        jsonOnly,
        ...(options.humanReadableStreamEnabled === true
            ? { humanReadableStreamEnabled: true }
            : {}),
        materialWrite: options.materialWrite ??
            updatedArtifacts.some((artifact) => artifact.materialUpdate),
        primaryOutputArtifacts: normalizeCommandWriteSummaryArtifactPaths(options.primaryOutputArtifacts ?? []),
        updatedArtifacts
    };
}
function normalizeCommandWriteSummaryOutputMode(summary, options) {
    const jsonOnly = options.jsonOnly ??
        (options.format === undefined ? summary.jsonOnly : options.format === "json");
    const humanReadableStreamEnabled = options.humanReadableStreamEnabled ?? summary.humanReadableStreamEnabled;
    return normalizeCommandWriteSummary({
        ...summary,
        jsonOnly,
        humanReadableStreamEnabled,
        updatedArtifacts: summary.updatedArtifacts
    });
}
function shouldEmitHumanReadableCommandOutput(summary) {
    return !summary.jsonOnly || summary.humanReadableStreamEnabled === true;
}
function classifyReminderEligibilityFromCommandSummary(summary) {
    const terminalReasonCodes = new Set();
    const persistedReasonCodes = new Set();
    const outputSuppressed = addOutputSuppressionReasonCodes(summary, terminalReasonCodes, persistedReasonCodes);
    const terminalFamilyEligible = isTerminalCommandFamilyEligible(summary);
    const persistedFamilyEligible = isPersistedCommandFamilyEligible(summary.commandFamily);
    const persistedCandidateArtifacts = getPersistedCandidateArtifacts(summary);
    if (READ_ONLY_TERMINAL_ONLY_COMMAND_FAMILIES.has(summary.commandFamily)) {
        terminalReasonCodes.add("read_only_terminal_cadence_only");
    }
    if (terminalFamilyEligible) {
        terminalReasonCodes.add(TERMINAL_WRITE_REQUIRED_COMMAND_FAMILIES.has(summary.commandFamily)
            ? "terminal_write_required"
            : "terminal_command_family_eligible");
    }
    else if (TERMINAL_WRITE_REQUIRED_COMMAND_FAMILIES.has(summary.commandFamily)) {
        terminalReasonCodes.add("terminal_write_required");
    }
    else if (UNKNOWN_OR_FUTURE_COMMAND_FAMILIES.has(summary.commandFamily)) {
        terminalReasonCodes.add("terminal_unknown_command_family");
    }
    else {
        terminalReasonCodes.add("terminal_command_family_ineligible");
    }
    if (persistedCandidateArtifacts.length > 0) {
        persistedReasonCodes.add("persisted_material_coordination_write");
    }
    else {
        persistedReasonCodes.add("persisted_no_material_coordination_write");
    }
    if (persistedCandidateArtifacts.some((artifact) => materialUpdateForPath(summary, artifact.path)?.reason === "uncertain_coordination_write")) {
        persistedReasonCodes.add("uncertain_coordination_write_material");
    }
    if (!persistedFamilyEligible) {
        persistedReasonCodes.add(UNKNOWN_OR_FUTURE_COMMAND_FAMILIES.has(summary.commandFamily)
            ? "persisted_unknown_command_family"
            : "persisted_command_family_ineligible");
    }
    const terminalEligible = !outputSuppressed && terminalFamilyEligible;
    const persistedReminderEligible = !outputSuppressed &&
        persistedFamilyEligible &&
        persistedCandidateArtifacts.length > 0;
    const reasonCodes = uniqueReasonCodes([
        ...terminalReasonCodes,
        ...persistedReasonCodes
    ]);
    return {
        terminalEligible,
        terminalCadenceContributor: terminalEligible,
        persistedReminderEligible,
        terminalReasonCodes: uniqueReasonCodes([...terminalReasonCodes]),
        persistedReasonCodes: uniqueReasonCodes([...persistedReasonCodes]),
        reasonCodes,
        persistedCandidateArtifacts
    };
}
function normalizeCommandWriteSummaryArtifactPaths(artifactPaths) {
    const byPath = new Map();
    for (const artifactPath of artifactPaths) {
        const classification = classifyCommandWriteSummaryArtifact(artifactPath);
        byPath.set(classification.path, classification);
    }
    return [...byPath.values()]
        .sort(compareCommandWriteSummaryArtifactClassifications)
        .map((classification) => classification.path);
}
function normalizeCommandWriteSummaryArtifactUpdates(artifacts, options = {
    dryRun: false,
    jsonOnly: false
}) {
    const byPath = new Map();
    for (const artifact of artifacts) {
        const normalized = normalizeCommandWriteSummaryArtifactUpdate(artifact, options);
        byPath.set(normalized.path, normalized);
    }
    return [...byPath.values()].sort(compareCommandWriteSummaryArtifactUpdates);
}
function classifyMaterialArtifactUpdate(reason, isCoordinationArtifact, artifactKind = "unknown") {
    if (reason === "provided_material") {
        return true;
    }
    if (NON_MATERIAL_ARTIFACT_REASONS.has(reason)) {
        return false;
    }
    if (isCoordinationArtifact) {
        return MATERIAL_ARTIFACT_REASONS.has(reason);
    }
    return isTaskPairArtifactKind(artifactKind) &&
        MATERIAL_TASK_PAIR_REASONS.has(reason);
}
function isTaskPairArtifactKind(artifactKind) {
    return artifactKind === "task-definition" ||
        artifactKind === "implementation-summary";
}
function inferArtifactUpdateReason(options) {
    if (options.materialUpdate === true) {
        return "provided_material";
    }
    if (options.materialUpdate === false) {
        return "provided_non_material";
    }
    if (options.dryRun) {
        return "dry_run";
    }
    if (options.jsonOnly) {
        return "json_only";
    }
    const isTaskPairArtifact = isTaskPairArtifactKind(options.artifactKind);
    if (!options.isCoordinationArtifact && !isTaskPairArtifact) {
        return "non_coordination_artifact";
    }
    if (isTaskPairArtifact &&
        options.action !== "created" &&
        options.action !== "regenerated") {
        return "non_coordination_artifact";
    }
    switch (options.action) {
        case "created":
            return "accepted_create";
        case "regenerated":
            return "accepted_regeneration";
        case "rewritten":
            return "accepted_rewrite";
        case "changed":
            return "accepted_content_change";
        case "refreshed":
            return "accepted_refresh";
        case "kept":
            return "no_write";
        case "inspected":
        case "validated":
            return "read_only_output";
        case "bookkeeping":
            return "non_semantic_bookkeeping";
        case "unknown":
            return "uncertain_coordination_write";
    }
}
function actionFromReason(reason) {
    switch (reason) {
        case "accepted_create":
            return "created";
        case "accepted_regeneration":
            return "regenerated";
        case "accepted_rewrite":
        case "whitespace_only_rewrite":
            return "rewritten";
        case "accepted_content_change":
            return "changed";
        case "accepted_refresh":
            return "refreshed";
        case "read_only_output":
            return "inspected";
        case "non_semantic_bookkeeping":
            return "bookkeeping";
        case "dry_run":
        case "json_only":
        case "no_write":
        case "non_coordination_artifact":
        case "provided_material":
        case "provided_non_material":
        case "uncertain_coordination_write":
        case undefined:
            return null;
    }
}
function compareCommandWriteSummaryArtifactUpdates(a, b) {
    const classificationComparison = compareCommandWriteSummaryArtifactClassifications(a, b);
    if (classificationComparison !== 0) {
        return classificationComparison;
    }
    return a.reason.localeCompare(b.reason);
}
function compareCommandWriteSummaryArtifactClassifications(a, b) {
    return comparePlanningLayers(a.layer, b.layer) ||
        a.path.localeCompare(b.path);
}
function comparePlanningLayers(a, b) {
    return (PLANNING_LAYER_SORT_ORDER.get(a) ?? Number.MAX_SAFE_INTEGER) -
        (PLANNING_LAYER_SORT_ORDER.get(b) ?? Number.MAX_SAFE_INTEGER);
}
function addOutputSuppressionReasonCodes(summary, terminalReasonCodes, persistedReasonCodes) {
    if (summary.dryRun) {
        terminalReasonCodes.add("terminal_dry_run_suppression");
        persistedReasonCodes.add("persisted_dry_run_suppression");
        return true;
    }
    if (!shouldEmitHumanReadableCommandOutput(summary)) {
        terminalReasonCodes.add("terminal_json_only_suppression");
        persistedReasonCodes.add("persisted_json_only_suppression");
        return true;
    }
    if (summary.jsonOnly && summary.humanReadableStreamEnabled === true) {
        terminalReasonCodes.add("terminal_human_readable_stream_enabled");
        persistedReasonCodes.add("persisted_human_readable_stream_enabled");
    }
    return false;
}
function isTerminalCommandFamilyEligible(summary) {
    if (TERMINAL_ALWAYS_ELIGIBLE_COMMAND_FAMILIES.has(summary.commandFamily)) {
        return true;
    }
    if (TERMINAL_WRITE_REQUIRED_COMMAND_FAMILIES.has(summary.commandFamily)) {
        return hasAcceptedCommandWrite(summary);
    }
    return false;
}
function isPersistedCommandFamilyEligible(commandFamily) {
    return !UNKNOWN_OR_FUTURE_COMMAND_FAMILIES.has(commandFamily);
}
function hasAcceptedCommandWrite(summary) {
    if (summary.materialWrite) {
        return true;
    }
    return summary.updatedArtifacts.some((artifact) => {
        if (artifact.reason === "dry_run" ||
            artifact.reason === "json_only" ||
            artifact.reason === "read_only_output" ||
            artifact.reason === "whitespace_only_rewrite" ||
            artifact.reason === "non_semantic_bookkeeping" ||
            artifact.reason === "no_write" ||
            artifact.reason === "provided_non_material") {
            return false;
        }
        return artifact.action === "created" ||
            artifact.action === "regenerated" ||
            artifact.action === "rewritten" ||
            artifact.action === "changed" ||
            artifact.action === "refreshed" ||
            artifact.reason === "provided_material" ||
            artifact.reason === "uncertain_coordination_write";
    });
}
function getPersistedCandidateArtifacts(summary) {
    const byPath = new Map();
    for (const artifact of summary.updatedArtifacts) {
        if (artifact.isCoordinationArtifact && artifact.materialUpdate) {
            byPath.set(artifact.path, {
                path: artifact.path,
                layer: artifact.layer,
                artifactKind: artifact.artifactKind,
                isCoordinationArtifact: artifact.isCoordinationArtifact
            });
        }
    }
    return [...byPath.values()].sort(compareCommandWriteSummaryArtifactClassifications);
}
function materialUpdateForPath(summary, artifactPath) {
    return summary.updatedArtifacts.find((artifact) => artifact.path === artifactPath && artifact.materialUpdate) ?? null;
}
function uniqueReasonCodes(reasonCodes) {
    return [...new Set(reasonCodes)].sort();
}
function createClassification(pathValue, layer, artifactKind, isCoordinationArtifact) {
    return {
        path: pathValue,
        layer,
        artifactKind,
        isCoordinationArtifact
    };
}
function isInsidePlanningRoot(segments) {
    return segments.length >= 3 &&
        segments[0] === ".day-shift" &&
        segments[1] === "planning";
}
function isSliceOverviewPath(segments) {
    const hierarchySegments = planningHierarchySegments(segments);
    return hierarchySegments?.length === 2 &&
        (hierarchySegments[1] === "slice-overview.md" || hierarchySegments[1] === "overview.md");
}
function isPhaseOverviewPath(segments) {
    const hierarchySegments = planningHierarchySegments(segments);
    return hierarchySegments?.length === 4 &&
        hierarchySegments[1] === "phases" &&
        (hierarchySegments[3] === "phase-overview.md" || hierarchySegments[3] === "overview.md");
}
function isMilestoneOverviewPath(segments) {
    const hierarchySegments = planningHierarchySegments(segments);
    return hierarchySegments?.length === 6 &&
        hierarchySegments[1] === "phases" &&
        hierarchySegments[3] === "milestones" &&
        (hierarchySegments[5] === "milestone-overview.md" || hierarchySegments[5] === "overview.md");
}
function isMilestoneReconciliationPath(segments) {
    const hierarchySegments = planningHierarchySegments(segments);
    return hierarchySegments?.length === 6 &&
        hierarchySegments[1] === "phases" &&
        hierarchySegments[3] === "milestones" &&
        hierarchySegments[5] === "reconciliation.md";
}
function isTaskDefinitionPath(segments) {
    return segments[segments.length - 1] === "task-definition.md" &&
        isTaskArtifactPath(segments);
}
function isImplementationSummaryPath(segments) {
    return segments[segments.length - 1] === "implementation-summary.md" &&
        isTaskArtifactPath(segments);
}
function isTaskArtifactPath(segments) {
    const hierarchySegments = planningHierarchySegments(segments);
    if (hierarchySegments === null) {
        return false;
    }
    if (hierarchySegments.length === 4) {
        return hierarchySegments[1] === "tasks";
    }
    return hierarchySegments.length === 8 &&
        hierarchySegments[1] === "phases" &&
        hierarchySegments[3] === "milestones" &&
        hierarchySegments[5] === "tasks";
}
function planningHierarchySegments(segments) {
    if (!isInsidePlanningRoot(segments)) {
        return null;
    }
    return segments[2] === "governed"
        ? segments.slice(3)
        : segments.slice(2);
}
