"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkRemoteBaseBranchRef = checkRemoteBaseBranchRef;
exports.tryResolveRemoteBaseBranchGitCredentials = tryResolveRemoteBaseBranchGitCredentials;
exports.assertRemoteBaseBranchPresent = assertRemoteBaseBranchPresent;
exports.formatRemoteBaseBranchMissingMessage = formatRemoteBaseBranchMissingMessage;
exports.formatRemoteBaseBranchCheckFailedMessage = formatRemoteBaseBranchCheckFailedMessage;
const node_path_1 = __importDefault(require("node:path"));
const catalog_1 = require("../i18n/catalog");
const native_git_cli_1 = require("./native-git-cli");
const remote_discovery_1 = require("./remote-discovery");
const remote_url_safety_1 = require("./remote-url-safety");
async function checkRemoteBaseBranchRef(input) {
    const cwd = node_path_1.default.resolve(input.cwd);
    const locale = input.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    const unsafeRemoteUrlMessage = await readUnsafeRemoteUrlMessage(cwd, input.remoteName);
    if (unsafeRemoteUrlMessage !== null) {
        return {
            kind: "check_failed",
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
            cwd,
            message: formatRemoteBaseBranchCheckFailedMessage({
                cwd,
                remoteName: input.remoteName,
                baseBranch: input.baseBranch,
                locale,
                message: unsafeRemoteUrlMessage,
                ...(input.projectRef !== undefined
                    ? { projectRef: input.projectRef }
                    : {}),
            }),
        };
    }
    const result = await (0, native_git_cli_1.runNativeGitCommand)({
        args: ["ls-remote", "--heads", input.remoteName, input.baseBranch],
        cwd,
        credentials: input.credentials ?? null,
        timeoutMs: input.timeoutMs ?? 15_000,
        allowNonZeroExit: true,
    });
    if (result.exitCode !== 0) {
        const message = result.stderr.trim() ||
            result.stdout.trim() ||
            (0, catalog_1.translate)(locale, "remoteBaseBranch.checkFailedFallback");
        return {
            kind: "check_failed",
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
            cwd,
            message: formatRemoteBaseBranchCheckFailedMessage({
                cwd,
                remoteName: input.remoteName,
                baseBranch: input.baseBranch,
                locale,
                message,
                ...(input.projectRef !== undefined
                    ? { projectRef: input.projectRef }
                    : {}),
            }),
        };
    }
    if (!remoteBaseBranchExists(result.stdout, input.baseBranch)) {
        return {
            kind: "missing",
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
            cwd,
            message: formatRemoteBaseBranchMissingMessage({
                cwd,
                remoteName: input.remoteName,
                baseBranch: input.baseBranch,
                locale,
                ...(input.projectRef !== undefined
                    ? { projectRef: input.projectRef }
                    : {}),
            }),
        };
    }
    return {
        kind: "present",
        remoteName: input.remoteName,
        baseBranch: input.baseBranch,
        cwd,
    };
}
async function tryResolveRemoteBaseBranchGitCredentials(authProvider, target) {
    try {
        return await authProvider.getGitCredentials(target);
    }
    catch {
        return null;
    }
}
function assertRemoteBaseBranchPresent(result) {
    if (result.kind === "present") {
        return;
    }
    throw new Error(result.message);
}
function formatRemoteBaseBranchMissingMessage(input) {
    const locale = input.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    return [
        (0, catalog_1.translate)(locale, "remoteBaseBranch.missing", {
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
            cwd: node_path_1.default.resolve(input.cwd),
            projectRef: input.projectRef ?? "-",
        }),
        (0, catalog_1.translate)(locale, "remoteBaseBranch.repairHint", {
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
        }),
        ...(input.includePartialCreateHint
            ? [(0, catalog_1.translate)(locale, "remoteBaseBranch.partialCreateHint")]
            : []),
    ].join(" ");
}
function formatRemoteBaseBranchCheckFailedMessage(input) {
    const locale = input.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    return [
        (0, catalog_1.translate)(locale, "remoteBaseBranch.checkFailed", {
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
            cwd: node_path_1.default.resolve(input.cwd),
            message: input.message,
            projectRef: input.projectRef ?? "-",
        }),
        (0, catalog_1.translate)(locale, "remoteBaseBranch.repairHint", {
            remoteName: input.remoteName,
            baseBranch: input.baseBranch,
        }),
    ].join(" ");
}
async function readUnsafeRemoteUrlMessage(cwd, remoteName) {
    const remoteUrl = await (0, remote_discovery_1.discoverGitRemoteUrl)(cwd, remoteName);
    if (remoteUrl === null) {
        return null;
    }
    try {
        (0, remote_url_safety_1.assertRemoteUrlDoesNotContainCredentials)(remoteUrl);
        return null;
    }
    catch (error) {
        return error instanceof Error ? error.message : String(error);
    }
}
function remoteBaseBranchExists(stdout, baseBranch) {
    const expectedRef = `refs/heads/${baseBranch}`;
    return stdout
        .trim()
        .split(/\r?\n/)
        .some((line) => line.split(/\s+/).at(1) === expectedRef);
}
