"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkReleaseRepositoryState = checkReleaseRepositoryState;
const node_child_process_1 = require("node:child_process");
const node_path_1 = __importDefault(require("node:path"));
function checkReleaseRepositoryState(options) {
    const repositoryRoot = node_path_1.default.resolve(options.repositoryRoot);
    const gitStatus = (0, node_child_process_1.spawnSync)("git", ["-C", repositoryRoot, "status", "--porcelain=v1", "--untracked-files=all"], {
        encoding: "utf8"
    });
    if (gitStatus.status !== 0) {
        const detail = gitStatus.stderr.trim() || gitStatus.stdout.trim() || "git status did not complete successfully.";
        return {
            ok: false,
            dirtyPaths: ["(repository-state-unavailable)"],
            ignoredGeneratedOutputPaths: [],
            message: `Release repository state could not be verified: ${detail}`,
            correctiveAction: "Run release commands from a git checkout with a verifiably clean repository state."
        };
    }
    const dirtyPaths = parsePorcelainPaths(gitStatus.stdout);
    const generatedOutputRoot = normalizeRepositoryRelativePath(node_path_1.default.relative(repositoryRoot, node_path_1.default.resolve(repositoryRoot, normalizeOutputDir(options.outputDir))));
    const ignoredGeneratedOutputPaths = dirtyPaths.filter((dirtyPath) => isPathWithinOrEqual(dirtyPath, generatedOutputRoot));
    const blockingDirtyPaths = dirtyPaths.filter((dirtyPath) => !isPathWithinOrEqual(dirtyPath, generatedOutputRoot));
    if (blockingDirtyPaths.length > 0 && options.allowDirty === true) {
        return {
            ok: true,
            dirtyPaths: blockingDirtyPaths,
            ignoredGeneratedOutputPaths
        };
    }
    if (blockingDirtyPaths.length > 0) {
        const sample = blockingDirtyPaths.slice(0, 10).join(", ");
        return {
            ok: false,
            dirtyPaths: blockingDirtyPaths,
            ignoredGeneratedOutputPaths,
            message: `Release repository state is dirty: ${sample}`,
            correctiveAction: "Commit, stash, or revert source and configuration changes before retrying, use release cleanup for generated release output, or rerun release build with --dirty for local engineering output."
        };
    }
    return {
        ok: true,
        dirtyPaths: [],
        ignoredGeneratedOutputPaths
    };
}
function normalizeOutputDir(value) {
    if (typeof value !== "string" || value.trim().length === 0) {
        return "release";
    }
    return value;
}
function parsePorcelainPaths(output) {
    return output
        .split(/\r?\n/)
        .map((line) => line.trimEnd())
        .filter((line) => line.length > 0)
        .flatMap((line) => parsePorcelainLinePath(line))
        .map(normalizeRepositoryRelativePath)
        .filter((dirtyPath) => dirtyPath.length > 0);
}
function parsePorcelainLinePath(line) {
    const pathText = line.slice(3);
    if (pathText.includes(" -> ")) {
        return pathText.split(" -> ").map(unquoteGitPath);
    }
    return [unquoteGitPath(pathText)];
}
function unquoteGitPath(value) {
    const trimmed = value.trim();
    if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
        return trimmed.slice(1, -1);
    }
    return trimmed;
}
function normalizeRepositoryRelativePath(value) {
    return value.split(node_path_1.default.sep).join("/");
}
function isPathWithinOrEqual(candidate, parent) {
    return candidate === parent || candidate.startsWith(`${parent}/`);
}
