"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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_DAILY_CREATE_TIME = void 0;
exports.isValidDailyCreateTime = isValidDailyCreateTime;
exports.normalizeDailyCreateTime = normalizeDailyCreateTime;
exports.getKstNowParts = getKstNowParts;
exports.isWorklogCreationDue = isWorklogCreationDue;
exports.renderWorklogTemplate = renderWorklogTemplate;
exports.upgradeLegacyWorklogContent = upgradeLegacyWorklogContent;
exports.ensureDailyWorklogFile = ensureDailyWorklogFile;
var promises_1 = require("node:fs/promises");
var node_path_1 = require("node:path");
var KST_TIME_ZONE = 'Asia/Seoul';
exports.DEFAULT_DAILY_CREATE_TIME = '18:00';
var DEFAULT_WORKLOG_TEMPLATE = "# YYYY-MM-DD \uC791\uC5C5\uC77C\uC9C0\n\n## \uC624\uB298 \uC791\uC5C5\n\n- \n\n## \uC774\uC288 \uBC0F \uD574\uACB0\n\n- \n\n## \uACB0\uC815 \uC0AC\uD56D\n\n- \n\n## \uC0C1\uC138 \uC791\uC5C5 \uB0B4\uC5ED\n\n- \n- \uC774 \uC139\uC158\uC5D0\uB294 \uD30C\uC77C \uBAA9\uB85D, \uACBD\uB85C \uB098\uC5F4, raw diff\uB97C \uC9C1\uC811 \uD480\uC5B4\uC4F0\uC9C0 \uB9D0\uACE0 \uC791\uC5C5 \uD750\uB984\uACFC \uD310\uB2E8\uB9CC \uC815\uB9AC\n- \uD30C\uC77C \uBAA9\uB85D\uC740 \uBCC0\uACBD/\uC2E0\uADDC \uD30C\uC77C \uC139\uC158\uC5D0, raw diff\uB294 \uC18C\uC2A4 \uC139\uC158\uC5D0\uB9CC \uAE30\uB85D\n\n## \uC2A4\uD06C\uB9B0\uC0F7\n\n- \uC804\uCCB4 \uD654\uBA74 \uC2A4\uD06C\uB9B0\uC0F7 1\uC7A5\uC740 \uD544\uC218\n- \uC704\uC82F/\uCEF4\uD3EC\uB10C\uD2B8 \uB2E8\uC704 \uBD80\uBD84 \uC2A4\uD06C\uB9B0\uC0F7\uC740 \uD544\uC694\uD55C \uB9CC\uD07C \uCD94\uAC00\n- \uC800\uC7A5\uC18C \uAE30\uC900 \uC5F0\uACB0\uB41C \uC2A4\uD06C\uB9B0\uC0F7\uC774 \uC5C6\uC73C\uBA74 \uC791\uC5C5 \uC885\uB8CC \uC804 \uBC18\uB4DC\uC2DC \uCC44\uC6C0\n\n## \uC18C\uC2A4\n\n### \uD30C\uC77C 1: `path/to/file.tsx`\n\n- \uBCC0\uACBD \uB610\uB294 \uC2E0\uADDC \uCD94\uAC00 \uBAA9\uC801\uACFC \uD575\uC2EC \uB0B4\uC6A9\uC744 \uD55C \uC904\uB85C \uC815\uB9AC\n- `\uC0C1\uC138 \uC791\uC5C5 \uB0B4\uC5ED`\uC5D0\uB294 \uD30C\uC77C \uBAA9\uB85D\uC774\uB098 raw diff\uB97C \uB2E4\uC2DC \uC4F0\uC9C0 \uC54A\uC74C\n- `\uC18C\uC2A4` \uD0ED\uC5D0\uC11C Codex preview \uC2A4\uD0C0\uC77C\uC758 `\uC804\uCCB4\uC18C\uC2A4 / raw diff` \uC804\uD658\uC744 \uC81C\uACF5\uD558\uBBC0\uB85C \uC5EC\uAE30\uC5D0\uB294 \uD30C\uC77C\uBCC4 raw diff \uC704\uC8FC\uB85C \uB0A8\uAE40\n\n```diff\n# \uC774 \uD30C\uC77C\uC758 raw diff\n- before\n+ after\n```\n\n### \uD30C\uC77C 2: `path/to/another-file.ts`\n\n- \uD544\uC694 \uC5C6\uC73C\uBA74 \uC774 \uC139\uC158\uC740 \uC0AD\uC81C\n\n## \uC2E4\uD589 \uCEE4\uB9E8\uB4DC\n\n```bash\n```\n\n## \uBCC0\uACBD/\uC2E0\uADDC \uD30C\uC77C\n\n- \n";
var OBSOLETE_WORKLOG_SECTION_TITLES = new Set([
    '커밋 목록',
    '변경 요약',
    '변경 통계',
    '라인 통계',
]);
function extractKstParts(date) {
    var _a, _b, _c, _d, _e;
    var parts = new Intl.DateTimeFormat('en-CA', {
        timeZone: KST_TIME_ZONE,
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false,
    }).formatToParts(date);
    var values = Object.fromEntries(parts.filter(function (part) { return part.type !== 'literal'; }).map(function (part) { return [part.type, part.value]; }));
    return {
        year: Number((_a = values.year) !== null && _a !== void 0 ? _a : '0'),
        month: Number((_b = values.month) !== null && _b !== void 0 ? _b : '0'),
        day: Number((_c = values.day) !== null && _c !== void 0 ? _c : '0'),
        hour: Number((_d = values.hour) !== null && _d !== void 0 ? _d : '0'),
        minute: Number((_e = values.minute) !== null && _e !== void 0 ? _e : '0'),
    };
}
function isValidDailyCreateTime(value) {
    return typeof value === 'string' && /^\d{2}:\d{2}$/.test(value);
}
function normalizeDailyCreateTime(value) {
    return isValidDailyCreateTime(value) ? value : exports.DEFAULT_DAILY_CREATE_TIME;
}
function getKstNowParts(date) {
    if (date === void 0) { date = new Date(); }
    var _a = extractKstParts(date), year = _a.year, month = _a.month, day = _a.day, hour = _a.hour, minute = _a.minute;
    return {
        dateKey: "".concat(String(year).padStart(4, '0'), "-").concat(String(month).padStart(2, '0'), "-").concat(String(day).padStart(2, '0')),
        minutesOfDay: hour * 60 + minute,
    };
}
function isWorklogCreationDue(now, dailyCreateTime, alreadyExecutedToday) {
    if (alreadyExecutedToday) {
        return false;
    }
    var _a = normalizeDailyCreateTime(dailyCreateTime).split(':').map(function (value) { return Number(value); }), hours = _a[0], minutes = _a[1];
    var nowParts = getKstNowParts(now);
    return nowParts.minutesOfDay >= (hours * 60 + minutes);
}
function renderWorklogTemplate(template, dateKey) {
    return template.replaceAll('YYYY-MM-DD', dateKey);
}
function normalizeLevelTwoHeading(line) {
    var _a, _b;
    var match = line.match(/^##\s+([^\n]+)$/m);
    if (!match) {
        return '';
    }
    return (_b = (_a = match[1]) === null || _a === void 0 ? void 0 : _a.replace(/\s+\(.*\)\s*$/u, '').trim()) !== null && _b !== void 0 ? _b : '';
}
function stripObsoleteWorklogSections(content) {
    var sections = content.split(/\n(?=##\s+)/);
    var preservedSections = sections.filter(function (section) {
        var normalizedHeading = normalizeLevelTwoHeading(section);
        return !OBSOLETE_WORKLOG_SECTION_TITLES.has(normalizedHeading);
    });
    return "".concat(preservedSections.join('\n\n').replace(/\n{3,}/g, '\n\n').trimEnd(), "\n");
}
var LEGACY_SOURCE_SECTION = "## \uC18C\uC2A4\n\n- \uC694\uC57D \uC124\uBA85\n- `path/to/file.tsx`: \uBCC0\uACBD \uB610\uB294 \uC2E0\uADDC \uCD94\uAC00 \uBAA9\uC801\uACFC \uD575\uC2EC \uB0B4\uC6A9\uC744 \uD55C \uC904\uB85C \uC815\uB9AC\n\n```diff\n# \uD575\uC2EC diff\uB97C 1~3\uAC1C \uBE14\uB85D\uC73C\uB85C \uAE30\uB85D\n- before\n+ after\n```";
var FILE_SCOPED_SOURCE_SECTION = "## \uC18C\uC2A4\n\n### \uD30C\uC77C 1: `path/to/file.tsx`\n\n- \uBCC0\uACBD \uB610\uB294 \uC2E0\uADDC \uCD94\uAC00 \uBAA9\uC801\uACFC \uD575\uC2EC \uB0B4\uC6A9\uC744 \uD55C \uC904\uB85C \uC815\uB9AC\n- `\uC0C1\uC138 \uC791\uC5C5 \uB0B4\uC5ED`\uC5D0\uB294 \uD30C\uC77C \uBAA9\uB85D\uC774\uB098 raw diff\uB97C \uB2E4\uC2DC \uC4F0\uC9C0 \uC54A\uC74C\n- `\uC18C\uC2A4` \uD0ED\uC5D0\uC11C Codex preview \uC2A4\uD0C0\uC77C\uC758 `\uC804\uCCB4\uC18C\uC2A4 / raw diff` \uC804\uD658\uC744 \uC81C\uACF5\uD558\uBBC0\uB85C \uC5EC\uAE30\uC5D0\uB294 \uD30C\uC77C\uBCC4 raw diff \uC704\uC8FC\uB85C \uB0A8\uAE40\n\n```diff\n# \uC774 \uD30C\uC77C\uC758 raw diff\n- before\n+ after\n```\n\n### \uD30C\uC77C 2: `path/to/another-file.ts`\n\n- \uD544\uC694 \uC5C6\uC73C\uBA74 \uC774 \uC139\uC158\uC740 \uC0AD\uC81C";
function upgradeLegacyWorklogContent(content) {
    var upgradedContent = content;
    if (upgradedContent.includes(LEGACY_SOURCE_SECTION)) {
        upgradedContent = upgradedContent.replace(LEGACY_SOURCE_SECTION, FILE_SCOPED_SOURCE_SECTION);
    }
    upgradedContent = upgradedContent
        .replace('## 상세 작업 내역\n\n- ', "## \uC0C1\uC138 \uC791\uC5C5 \uB0B4\uC5ED\n\n- \n- \uC774 \uC139\uC158\uC5D0\uB294 \uD30C\uC77C \uBAA9\uB85D, \uACBD\uB85C \uB098\uC5F4, raw diff\uB97C \uC9C1\uC811 \uD480\uC5B4\uC4F0\uC9C0 \uB9D0\uACE0 \uC791\uC5C5 \uD750\uB984\uACFC \uD310\uB2E8\uB9CC \uC815\uB9AC\n- \uD30C\uC77C \uBAA9\uB85D\uC740 `## \uBCC0\uACBD/\uC2E0\uADDC \uD30C\uC77C`, raw diff\uB294 `## \uC18C\uC2A4`\uC5D0\uC11C\uB9CC \uAE30\uB85D")
        .replace('## 스크린샷\n\n- 저장소 기준 연결된 스크린샷 없음', "## \uC2A4\uD06C\uB9B0\uC0F7\n\n- \uC804\uCCB4 \uD654\uBA74 \uC2A4\uD06C\uB9B0\uC0F7 1\uC7A5\uC740 \uD544\uC218\n- \uC704\uC82F/\uCEF4\uD3EC\uB10C\uD2B8 \uB2E8\uC704 \uBD80\uBD84 \uC2A4\uD06C\uB9B0\uC0F7\uC740 \uD544\uC694\uD55C \uB9CC\uD07C \uCD94\uAC00\n- \uC800\uC7A5\uC18C \uAE30\uC900 \uC5F0\uACB0\uB41C \uC2A4\uD06C\uB9B0\uC0F7\uC774 \uC5C6\uC73C\uBA74 \uC791\uC5C5 \uC885\uB8CC \uC804 \uBC18\uB4DC\uC2DC \uCC44\uC6C0")
        .replaceAll('# 이 파일의 핵심 diff', '# 이 파일의 raw diff')
        .replaceAll('`작업일지` 탭에는 중복 파일 목록을 다시 쓰지 않아도 됨', '`상세 작업 내역`에는 파일 목록이나 raw diff를 다시 쓰지 않음')
        .replaceAll('`소스` 탭에서 전체소스/diff를 전환해 보므로 여기에는 파일별 raw diff 위주로 남김', '`소스` 탭에서 Codex preview 스타일의 `전체소스 / raw diff` 전환을 제공하므로 여기에는 파일별 raw diff 위주로 남김');
    return stripObsoleteWorklogSections(upgradedContent);
}
function readWorklogTemplate(repoPath) {
    return __awaiter(this, void 0, void 0, function () {
        var templatePath, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    templatePath = node_path_1.default.join(repoPath, 'docs', 'templates', 'worklog-template.md');
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, (0, promises_1.readFile)(templatePath, 'utf8')];
                case 2: return [2 /*return*/, _b.sent()];
                case 3:
                    _a = _b.sent();
                    return [2 /*return*/, DEFAULT_WORKLOG_TEMPLATE];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function ensureDailyWorklogFile(repoPath, dateKey) {
    return __awaiter(this, void 0, void 0, function () {
        var worklogPath, existingContent, upgradedContent, _a, template;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    worklogPath = node_path_1.default.join(repoPath, 'docs', 'worklogs', "".concat(dateKey, ".md"));
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 6, , 10]);
                    return [4 /*yield*/, (0, promises_1.access)(worklogPath)];
                case 2:
                    _b.sent();
                    return [4 /*yield*/, (0, promises_1.readFile)(worklogPath, 'utf8')];
                case 3:
                    existingContent = _b.sent();
                    upgradedContent = upgradeLegacyWorklogContent(existingContent);
                    if (!(upgradedContent !== existingContent)) return [3 /*break*/, 5];
                    return [4 /*yield*/, (0, promises_1.writeFile)(worklogPath, upgradedContent, 'utf8')];
                case 4:
                    _b.sent();
                    _b.label = 5;
                case 5: return [2 /*return*/, worklogPath];
                case 6:
                    _a = _b.sent();
                    return [4 /*yield*/, readWorklogTemplate(repoPath)];
                case 7:
                    template = _b.sent();
                    return [4 /*yield*/, (0, promises_1.mkdir)(node_path_1.default.dirname(worklogPath), { recursive: true })];
                case 8:
                    _b.sent();
                    return [4 /*yield*/, (0, promises_1.writeFile)(worklogPath, renderWorklogTemplate(template, dateKey), 'utf8')];
                case 9:
                    _b.sent();
                    return [2 /*return*/, worklogPath];
                case 10: return [2 /*return*/];
            }
        });
    });
}
