"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BASE_WORKSPACES_DIRECTORY = void 0;
exports.getBaseWorkspacePath = getBaseWorkspacePath;
exports.ensureBaseWorkspace = ensureBaseWorkspace;
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const tracked_project_1 = require("../core/tracked-project");
const native_git_cli_1 = require("../git/native-git-cli");
const remote_url_1 = require("../platform/repository-host/remote-url");
const remote_base_branch_1 = require("../git/remote-base-branch");
const default_issue_workspace_manager_1 = require("./default-issue-workspace-manager");
exports.BASE_WORKSPACES_DIRECTORY = "__base";
function getBaseWorkspacePath(trackedProject, baseBranch, homeDirectory) {
    return node_path_1.default.join((0, default_issue_workspace_manager_1.getProjectWorkspaceRoot)(trackedProject, homeDirectory), exports.BASE_WORKSPACES_DIRECTORY, baseBranch);
}
async function ensureBaseWorkspace(input) {
    const workspacePath = getBaseWorkspacePath((0, tracked_project_1.toTrackedProjectRef)(input.config), input.config.repositoryHost.baseBranch, input.homeDirectory);
    await (0, promises_1.mkdir)(node_path_1.default.dirname(workspacePath), { recursive: true });
    const credentials = await input.authProvider.getGitCredentials(input.config.repositoryHost);
    const remoteUrl = (0, remote_url_1.buildRepositoryHostRemoteUrl)(input.config.repositoryHost);
    const syncInput = {
        workspacePath,
        baseBranch: input.config.repositoryHost.baseBranch,
        remoteName: input.config.repositoryHost.remoteName,
        gitClient: input.gitClient,
    };
    try {
        (0, remote_base_branch_1.assertRemoteBaseBranchPresent)(await (0, remote_base_branch_1.checkRemoteBaseBranchRef)({
            cwd: input.repositoryRoot,
            remoteName: input.config.repositoryHost.remoteName,
            baseBranch: input.config.repositoryHost.baseBranch,
            projectRef: input.config.repositoryHost.projectRef,
            credentials,
            locale: input.config.i18n.defaultLanguage,
        }));
        await input.gitClient.ensureWorkspaceClone({
            remoteUrl,
            workspacePath,
            baseBranch: input.config.repositoryHost.baseBranch,
            credentials,
        });
        try {
            await syncBaseWorkspaceToRemote(syncInput);
        }
        catch {
            await (0, promises_1.rm)(workspacePath, { recursive: true, force: true });
            await input.gitClient.ensureWorkspaceClone({
                remoteUrl,
                workspacePath,
                baseBranch: input.config.repositoryHost.baseBranch,
                credentials,
            });
            await syncBaseWorkspaceToRemote(syncInput);
        }
    }
    catch (error) {
        const detail = error instanceof Error ? ` ${error.message}` : "";
        throw new Error(`Failed to sync base workspace for ${input.config.repositoryHost.projectRef}: cwd=${workspacePath}, remote=${input.config.repositoryHost.remoteName}, missing or unreachable base ref=${input.config.repositoryHost.remoteName}/${input.config.repositoryHost.baseBranch}.${detail}`, { cause: error instanceof Error ? error : undefined });
    }
    return { path: workspacePath };
}
async function syncBaseWorkspaceToRemote(input) {
    const remoteRef = `${input.remoteName}/${input.baseBranch}`;
    await input.gitClient.fetch(input.workspacePath);
    await (0, native_git_cli_1.runNativeGit)(input.workspacePath, ["checkout", "-B", input.baseBranch, remoteRef], { suppressHooks: true });
    await (0, native_git_cli_1.runNativeGit)(input.workspacePath, ["reset", "--hard", remoteRef], {
        suppressHooks: true,
    });
    await (0, native_git_cli_1.runNativeGit)(input.workspacePath, ["clean", "-fd"], {
        suppressHooks: true,
    });
}
