"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertCleanWorktree = assertCleanWorktree;
exports.cleanAutomationWorktree = cleanAutomationWorktree;
exports.ensureBranchExists = ensureBranchExists;
exports.pushBranch = pushBranch;
exports.commitAllChanges = commitAllChanges;
exports.hasWorkingTreeChanges = hasWorkingTreeChanges;
exports.mergeBranch = mergeBranch;
exports.mergeBranchToRelease = mergeBranchToRelease;
exports.mergeReleaseToMain = mergeReleaseToMain;
exports.mergeIssueBranchToMain = mergeIssueBranchToMain;
exports.pullMainProjectBranch = pullMainProjectBranch;
exports.recreateReleaseBranchFromMain = recreateReleaseBranchFromMain;
var node_child_process_1 = require("node:child_process");
var promises_1 = require("node:fs/promises");
var node_fs_1 = require("node:fs");
var node_util_1 = require("node:util");
var env_js_1 = require("../config/env.js");
var execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
var gitCredentialSourcePath = '/root/.git-credentials';
var gitCredentialCachePath = '/tmp/work-server-git-credentials';
function prepareWritableCredentialStore() {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 3, , 4]);
                    return [4 /*yield*/, (0, promises_1.access)(gitCredentialSourcePath, node_fs_1.constants.R_OK)];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, (0, promises_1.copyFile)(gitCredentialSourcePath, gitCredentialCachePath)];
                case 2:
                    _b.sent();
                    return [2 /*return*/, gitCredentialCachePath];
                case 3:
                    _a = _b.sent();
                    return [2 /*return*/, null];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function runGit(repoPath, args) {
    return __awaiter(this, void 0, void 0, function () {
        var credentialStorePath, gitArgs, env, _a, stdout, stderr;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, prepareWritableCredentialStore()];
                case 1:
                    credentialStorePath = _b.sent();
                    gitArgs = ['-c', "safe.directory=".concat(repoPath)];
                    env = (0, env_js_1.getEnv)();
                    if (credentialStorePath) {
                        gitArgs.push('-c', "credential.helper=store --file=".concat(credentialStorePath));
                    }
                    return [4 /*yield*/, execFileAsync('git', ['-c', "safe.directory=".concat(repoPath), '-C', repoPath, 'config', 'user.name', env.PLAN_GIT_USER_NAME], {
                            encoding: 'utf8',
                        })];
                case 2:
                    _b.sent();
                    return [4 /*yield*/, execFileAsync('git', ['-c', "safe.directory=".concat(repoPath), '-C', repoPath, 'config', 'user.email', env.PLAN_GIT_USER_EMAIL], {
                            encoding: 'utf8',
                        })];
                case 3:
                    _b.sent();
                    return [4 /*yield*/, execFileAsync('git', __spreadArray(__spreadArray(__spreadArray([], gitArgs, true), ['-C', repoPath], false), args, true), {
                            encoding: 'utf8',
                        })];
                case 4:
                    _a = _b.sent(), stdout = _a.stdout, stderr = _a.stderr;
                    return [2 /*return*/, {
                            stdout: stdout.trim(),
                            stderr: stderr.trim(),
                        }];
            }
        });
    });
}
function assertBranchExists(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, runGit(repoPath, ['rev-parse', '--verify', branchName])];
                case 1:
                    _b.sent();
                    return [3 /*break*/, 3];
                case 2:
                    _a = _b.sent();
                    throw new Error("".concat(branchName, " \uBE0C\uB79C\uCE58\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uBA3C\uC800 ").concat(branchName, " \uBE0C\uB79C\uCE58\uB97C \uC0DD\uC131\uD55C \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694."));
                case 3: return [2 /*return*/];
            }
        });
    });
}
function hasLocalBranch(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, runGit(repoPath, ['rev-parse', '--verify', '--quiet', branchName])];
                case 1:
                    _b.sent();
                    return [2 /*return*/, true];
                case 2:
                    _a = _b.sent();
                    return [2 /*return*/, false];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function hasRemoteBranch(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, runGit(repoPath, ['rev-parse', '--verify', '--quiet', "refs/remotes/origin/".concat(branchName)])];
                case 1:
                    _b.sent();
                    return [2 /*return*/, true];
                case 2:
                    _a = _b.sent();
                    return [2 /*return*/, false];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function syncBranchWithRemote(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, ['fetch', 'origin', branchName])];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, hasRemoteBranch(repoPath, branchName)];
                case 2:
                    if (!(_b.sent())) {
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, hasLocalBranch(repoPath, branchName)];
                case 3:
                    if (!!(_b.sent())) return [3 /*break*/, 5];
                    return [4 /*yield*/, runGit(repoPath, ['branch', branchName, "origin/".concat(branchName)])];
                case 4:
                    _b.sent();
                    _b.label = 5;
                case 5:
                    _b.trys.push([5, 7, , 9]);
                    return [4 /*yield*/, runGit(repoPath, ['switch', branchName])];
                case 6:
                    _b.sent();
                    return [3 /*break*/, 9];
                case 7:
                    _a = _b.sent();
                    return [4 /*yield*/, runGit(repoPath, ['switch', '-C', branchName, "origin/".concat(branchName)])];
                case 8:
                    _b.sent();
                    return [3 /*break*/, 9];
                case 9: return [4 /*yield*/, runGit(repoPath, ['reset', '--hard', "origin/".concat(branchName)])];
                case 10:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function assertCleanWorktree(repoPath) {
    return __awaiter(this, void 0, void 0, function () {
        var stdout;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, ['status', '--porcelain'])];
                case 1:
                    stdout = (_a.sent()).stdout;
                    if (stdout) {
                        throw new Error('Git 작업 디렉터리가 깨끗하지 않습니다. 변경 사항을 정리한 뒤 다시 시도해 주세요.');
                    }
                    return [2 /*return*/];
            }
        });
    });
}
function cleanAutomationWorktree(repoPath) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, ['reset', '--hard'])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, runGit(repoPath, ['clean', '-fd'])];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function ensureBranchExists(config, branchName, releaseTarget) {
    return __awaiter(this, void 0, void 0, function () {
        var baseBranch;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    baseBranch = config.mainBranch;
                    return [4 /*yield*/, assertCleanWorktree(config.repoPath)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, syncBranchWithRemote(config.repoPath, baseBranch)];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, assertBranchExists(config.repoPath, baseBranch)];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, runGit(config.repoPath, ['switch', baseBranch])];
                case 4:
                    _a.sent();
                    return [4 /*yield*/, runGit(config.repoPath, ['switch', '-C', branchName])];
                case 5:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function pushBranch(repoPath_1, branchName_1) {
    return __awaiter(this, arguments, void 0, function (repoPath, branchName, setUpstream) {
        if (setUpstream === void 0) { setUpstream = false; }
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, setUpstream ? ['push', '-u', 'origin', branchName] : ['push', 'origin', branchName])];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function deleteLocalBranch(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, runGit(repoPath, ['branch', '-D', branchName])];
                case 1:
                    _b.sent();
                    return [3 /*break*/, 3];
                case 2:
                    _a = _b.sent();
                    return [2 /*return*/];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function deleteRemoteBranch(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, runGit(repoPath, ['push', 'origin', '--delete', branchName])];
                case 1:
                    _b.sent();
                    return [3 /*break*/, 3];
                case 2:
                    _a = _b.sent();
                    return [2 /*return*/];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function commitAllChanges(repoPath, message) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, ['add', '-A'])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, runGit(repoPath, ['commit', '-m', message])];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function hasWorkingTreeChanges(repoPath) {
    return __awaiter(this, void 0, void 0, function () {
        var stdout;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, runGit(repoPath, ['status', '--porcelain'])];
                case 1:
                    stdout = (_a.sent()).stdout;
                    return [2 /*return*/, Boolean(stdout)];
            }
        });
    });
}
function isHotfixBranch(branchName) {
    return /^hotfix\//.test(branchName);
}
function isReleaseBranch(branchName, config) {
    return branchName === config.releaseBranch || /^release([/-]|$)/.test(branchName);
}
function shouldSquashMerge(sourceBranch, targetBranch, config) {
    return isHotfixBranch(sourceBranch) && (targetBranch === config.mainBranch || isReleaseBranch(targetBranch, config));
}
function assertAllowedMergeDirection(config, sourceBranch, targetBranch) {
    if (targetBranch === config.mainBranch &&
        sourceBranch !== config.releaseBranch &&
        sourceBranch !== config.mainBranch &&
        !isHotfixBranch(sourceBranch)) {
        throw new Error("\uBE0C\uB79C\uCE58 \uC804\uB7B5 \uC704\uBC18: ".concat(sourceBranch, " -> ").concat(targetBranch, " \uC9C1\uC811 \uBA38\uC9C0\uB294 \uD5C8\uC6A9\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. release \uBC18\uC601 \uD6C4 main\uC5D0 \uBC18\uC601\uD574 \uC8FC\uC138\uC694."));
    }
}
function mergeBranch(config, sourceBranch, targetBranch) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    assertAllowedMergeDirection(config, sourceBranch, targetBranch);
                    return [4 /*yield*/, assertCleanWorktree(config.repoPath)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, syncBranchWithRemote(config.repoPath, targetBranch)];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, assertBranchExists(config.repoPath, targetBranch)];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, assertBranchExists(config.repoPath, sourceBranch)];
                case 4:
                    _a.sent();
                    if (!(sourceBranch === config.releaseBranch || sourceBranch === config.mainBranch)) return [3 /*break*/, 6];
                    return [4 /*yield*/, syncBranchWithRemote(config.repoPath, sourceBranch)];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6: return [4 /*yield*/, runGit(config.repoPath, ['switch', targetBranch])];
                case 7:
                    _a.sent();
                    if (!shouldSquashMerge(sourceBranch, targetBranch, config)) return [3 /*break*/, 10];
                    return [4 /*yield*/, runGit(config.repoPath, ['merge', '--squash', sourceBranch])];
                case 8:
                    _a.sent();
                    return [4 /*yield*/, runGit(config.repoPath, ['commit', '-m', "merge: ".concat(sourceBranch, " -> ").concat(targetBranch, " (squash)")])];
                case 9:
                    _a.sent();
                    return [2 /*return*/];
                case 10: return [4 /*yield*/, runGit(config.repoPath, ['merge', '--no-ff', sourceBranch, '-m', "merge: ".concat(sourceBranch, " -> ").concat(targetBranch)])];
                case 11:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function mergeBranchToRelease(config, branchName, releaseTarget) {
    return __awaiter(this, void 0, void 0, function () {
        var baseBranch;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    baseBranch = releaseTarget || config.releaseBranch;
                    return [4 /*yield*/, mergeBranch(config, branchName, baseBranch)];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function mergeReleaseToMain(config, releaseTarget) {
    return __awaiter(this, void 0, void 0, function () {
        var baseBranch;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    baseBranch = releaseTarget || config.releaseBranch;
                    return [4 /*yield*/, mergeBranch(config, baseBranch, config.mainBranch)];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function mergeIssueBranchToMain(config, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            throw new Error("\uBE0C\uB79C\uCE58 \uC804\uB7B5 \uC704\uBC18: ".concat(branchName, " -> ").concat(config.mainBranch, " \uC9C1\uC811 \uBA38\uC9C0\uB294 \uBE44\uD65C\uC131\uD654\uB418\uC5C8\uC2B5\uB2C8\uB2E4. release \uBE0C\uB79C\uCE58\uB97C \uD1B5\uD574 \uBC18\uC601\uD574 \uC8FC\uC138\uC694."));
        });
    });
}
function pullMainProjectBranch(repoPath, branchName) {
    return __awaiter(this, void 0, void 0, function () {
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, assertCleanWorktree(repoPath)];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, runGit(repoPath, ['fetch', 'origin', branchName])];
                case 2:
                    _b.sent();
                    _b.label = 3;
                case 3:
                    _b.trys.push([3, 5, , 7]);
                    return [4 /*yield*/, runGit(repoPath, ['switch', branchName])];
                case 4:
                    _b.sent();
                    return [3 /*break*/, 7];
                case 5:
                    _a = _b.sent();
                    return [4 /*yield*/, runGit(repoPath, ['switch', '-C', branchName, "origin/".concat(branchName)])];
                case 6:
                    _b.sent();
                    return [3 /*break*/, 7];
                case 7: return [4 /*yield*/, runGit(repoPath, ['pull', '--ff-only', 'origin', branchName])];
                case 8:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function recreateReleaseBranchFromMain(config, releaseTarget) {
    return __awaiter(this, void 0, void 0, function () {
        var targetBranch;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    targetBranch = releaseTarget || config.releaseBranch;
                    if (targetBranch === config.mainBranch) {
                        throw new Error('release 브랜치를 main 브랜치와 동일하게 재생성할 수 없습니다.');
                    }
                    return [4 /*yield*/, assertCleanWorktree(config.repoPath)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, syncBranchWithRemote(config.repoPath, config.mainBranch)];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, assertBranchExists(config.repoPath, config.mainBranch)];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, runGit(config.repoPath, ['switch', config.mainBranch])];
                case 4:
                    _a.sent();
                    return [4 /*yield*/, deleteLocalBranch(config.repoPath, targetBranch)];
                case 5:
                    _a.sent();
                    return [4 /*yield*/, deleteRemoteBranch(config.repoPath, targetBranch)];
                case 6:
                    _a.sent();
                    return [4 /*yield*/, runGit(config.repoPath, ['switch', '-C', targetBranch, config.mainBranch])];
                case 7:
                    _a.sent();
                    return [4 /*yield*/, pushBranch(config.repoPath, targetBranch, true)];
                case 8:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
