"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.inspectMilestoneScaffoldRecoveryPairSync = inspectMilestoneScaffoldRecoveryPairSync;
const node_fs_1 = __importDefault(require("node:fs"));
const scaffold_application_1 = require("./scaffold-application");
/**
 * Classifies only an exact, untouched legacy milestone scaffold pair as
 * recoverable. Status/provenance checks keep failures specific, while complete
 * byte equality is the authority that prevents authored edits from being
 * overwritten.
 */
function inspectMilestoneScaffoldRecoveryPairSync(options) {
    const issues = [];
    const overviewText = readRequiredFile(options.overviewPath, "milestone overview", issues);
    const reconciliationText = readRequiredFile(options.reconciliationPath, "milestone reconciliation", issues);
    if (node_fs_1.default.lstatSync(options.tasksDirectoryPath, { throwIfNoEntry: false }) !== undefined) {
        issues.push(`Task workspace '${options.tasksDirectoryPath}' already exists; generated milestone scaffold recovery cannot replace a parent after child work begins.`);
    }
    if (overviewText !== null) {
        requireTopLevelScalar(overviewText, "status", "draft", "Milestone overview", issues);
        requireTopLevelScalar(overviewText, "workflow_provenance", "cli", "Milestone overview", issues);
        requireMilestoneNewCommand(overviewText, "Milestone overview", issues);
        if (overviewText !== options.expectedLegacyOverviewText
            && overviewText !== options.expectedRecoveredOverviewText) {
            issues.push("Milestone overview bytes do not match the exact legacy CLI-generated scaffold; authored or otherwise changed content is never recoverable through this command.");
        }
    }
    if (reconciliationText !== null) {
        requireTopLevelScalar(reconciliationText, "status", "draft", "Milestone reconciliation", issues);
        requireTopLevelScalar(reconciliationText, "reconciliation_status", "pending", "Milestone reconciliation", issues);
        requireTopLevelScalar(reconciliationText, "workflow_provenance", "cli", "Milestone reconciliation", issues);
        requireTopLevelScalar(reconciliationText, "workflow_manual_exception", "", "Milestone reconciliation", issues);
        requireMilestoneNewCommand(reconciliationText, "Milestone reconciliation", issues);
        if (reconciliationText !== options.expectedLegacyReconciliationText
            && reconciliationText !== options.expectedRecoveredReconciliationText) {
            issues.push("Milestone reconciliation bytes do not match the exact default pending CLI-generated artifact; authored or reviewed reconciliation content is never recoverable through this command.");
        }
    }
    const alreadyRecovered = overviewText !== null
        && reconciliationText !== null
        && overviewText === options.expectedRecoveredOverviewText
        && reconciliationText === options.expectedRecoveredReconciliationText;
    const eligible = issues.length === 0;
    return {
        eligible,
        action: !eligible ? "blocked" : alreadyRecovered ? "no-write" : "replace",
        issues: uniqueValues(issues),
        overviewText,
        reconciliationText,
        overviewExpectedRevision: overviewText === null ? null : (0, scaffold_application_1.planningScaffoldContentRevision)(overviewText),
        reconciliationExpectedRevision: reconciliationText === null
            ? null
            : (0, scaffold_application_1.planningScaffoldContentRevision)(reconciliationText)
    };
}
function readRequiredFile(filePath, label, issues) {
    const stats = node_fs_1.default.statSync(filePath, { throwIfNoEntry: false });
    if (stats === undefined) {
        issues.push(`The ${label} '${filePath}' is missing; recovery requires an existing complete pair.`);
        return null;
    }
    if (!stats.isFile()) {
        issues.push(`The ${label} '${filePath}' is not a regular file.`);
        return null;
    }
    return node_fs_1.default.readFileSync(filePath, "utf8");
}
function requireTopLevelScalar(text, field, expected, label, issues) {
    const escapedField = field.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
    const match = text.match(new RegExp(`^${escapedField}:\\s*(.*)$`, "mu"));
    const observed = match === null ? null : parseScalar(match[1]);
    if (observed !== expected) {
        issues.push(`${label} must retain ${field}: ${expected === "" ? '""' : expected}; found ${observed === null ? "<missing>" : JSON.stringify(observed)}.`);
    }
}
function requireMilestoneNewCommand(text, label, issues) {
    const match = text.match(/^workflow_cli_command:\s*(.*)$/mu);
    const observed = match === null ? null : parseScalar(match[1]);
    if (observed === null || !/^day-shift milestone new(?:\s|$)/u.test(observed)) {
        issues.push(`${label} must retain a CLI generation command beginning with 'day-shift milestone new'.`);
    }
}
function parseScalar(value) {
    const trimmed = value.trim();
    if ((trimmed.startsWith('"') && trimmed.endsWith('"'))
        || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
        try {
            return trimmed.startsWith('"')
                ? JSON.parse(trimmed)
                : trimmed.slice(1, -1).replace(/''/gu, "'");
        }
        catch {
            return trimmed;
        }
    }
    return trimmed;
}
function uniqueValues(values) {
    return [...new Set(values)];
}
