"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.stringifyAutomationContextIds = stringifyAutomationContextIds;
exports.parseAutomationContextIds = parseAutomationContextIds;
exports.buildAutomationContextMarkdown = buildAutomationContextMarkdown;
exports.buildAutomationNoteSections = buildAutomationNoteSections;
exports.ensureSchedulePromptSnapshot = ensureSchedulePromptSnapshot;
var node_path_1 = require("node:path");
var promises_1 = require("node:fs/promises");
var env_js_1 = require("../config/env.js");
var automation_context_config_service_js_1 = require("./automation-context-config-service.js");
function stringifyAutomationContextIds(value) {
    return JSON.stringify((0, automation_context_config_service_js_1.normalizeAutomationContextSelection)(value));
}
function parseAutomationContextIds(value) {
    if (Array.isArray(value)) {
        return (0, automation_context_config_service_js_1.normalizeAutomationContextSelection)(value);
    }
    if (typeof value !== 'string') {
        return [];
    }
    var trimmed = value.trim();
    if (!trimmed) {
        return [];
    }
    try {
        var parsed = JSON.parse(trimmed);
        return (0, automation_context_config_service_js_1.normalizeAutomationContextSelection)(parsed);
    }
    catch (_a) {
        return (0, automation_context_config_service_js_1.normalizeAutomationContextSelection)(trimmed);
    }
}
function buildAutomationContextMarkdown(contexts, selectedContextIds) {
    var resolvedContexts = (0, automation_context_config_service_js_1.resolveAutomationContexts)(contexts, selectedContextIds);
    if (resolvedContexts.length === 0) {
        return '선택된 자동화 Context 없음';
    }
    return resolvedContexts
        .map(function (item) { return ["### ".concat(item.title), item.content.trim() || '(내용 없음)'].join('\n'); })
        .join('\n\n');
}
function buildAutomationNoteSections(options) {
    return __awaiter(this, void 0, void 0, function () {
        var availableContexts, _a, lines;
        var _b, _c, _d, _e, _f, _g;
        return __generator(this, function (_h) {
            switch (_h.label) {
                case 0:
                    if (!((_b = options.availableContexts) !== null && _b !== void 0)) return [3 /*break*/, 1];
                    _a = _b;
                    return [3 /*break*/, 3];
                case 1: return [4 /*yield*/, (0, automation_context_config_service_js_1.getAutomationContextsConfig)()];
                case 2:
                    _a = (_h.sent());
                    _h.label = 3;
                case 3:
                    availableContexts = _a;
                    lines = __spreadArray(__spreadArray(__spreadArray([
                        '# 자동화 작업메모',
                        '',
                        ((_c = options.title) === null || _c === void 0 ? void 0 : _c.trim()) ? "- \uAC8C\uC2DC\uD310 \uC81C\uBAA9: ".concat(options.title.trim()) : null,
                        "- \uBA54\uBAA8 \uCD9C\uCC98: ".concat(options.sourceLabel),
                        ((_e = (_d = options.automationType) === null || _d === void 0 ? void 0 : _d.name) === null || _e === void 0 ? void 0 : _e.trim()) ? "- \uC120\uD0DD \uC790\uB3D9\uD654 \uC720\uD615: ".concat(options.automationType.name.trim()) : null,
                        '- 자동화 처리 원칙: 아래에서 선택된 자동화 Context만 우선 참조합니다.',
                        '',
                        '## 자동화 Context',
                        buildAutomationContextMarkdown(availableContexts, options.selectedContextIds),
                        ''
                    ], ((_f = options.extraSections) !== null && _f !== void 0 ? _f : []), true), [
                        '## 요청 본문',
                        options.requestContent.trim()
                    ], false), (((_g = options.attachments) === null || _g === void 0 ? void 0 : _g.length) ? __spreadArray(['', '## 첨부 파일'], options.attachments, true) : []), true);
                    return [2 /*return*/, lines.filter(function (line) { return line !== null && line !== undefined; }).join('\n')];
            }
        });
    });
}
function extractRequestedPaths(note) {
    var _a;
    var matches = (_a = note.match(/(?:[A-Za-z0-9._-]+[\/\\])+[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)?/g)) !== null && _a !== void 0 ? _a : [];
    return __spreadArray([], new Set(matches.map(function (item) { return item.replace(/\\/g, '/'); })), true);
}
function tryReadFile(filePath) {
    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*/, (0, promises_1.readFile)(filePath, 'utf8')];
                case 1: return [2 /*return*/, _b.sent()];
                case 2:
                    _a = _b.sent();
                    return [2 /*return*/, null];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function limitText(value, maxChars) {
    if (maxChars === void 0) { maxChars = 12000; }
    var normalized = value.trim();
    return normalized.length <= maxChars ? normalized : "".concat(normalized.slice(0, maxChars).trimEnd(), "\n\n...");
}
function getScheduleRepoRoot() {
    var env = (0, env_js_1.getEnv)();
    return env.SERVER_COMMAND_MAIN_PROJECT_ROOT || env.PLAN_MAIN_PROJECT_REPO_PATH || process.cwd();
}
function ensureSchedulePromptSnapshot(options) {
    return __awaiter(this, void 0, void 0, function () {
        var repoRoot, scheduleDir, requestPath, contextPath, manifestPath, requestedPaths, candidatePaths, uniqueRelativePaths, references, _i, uniqueRelativePaths_1, relativePath, absolutePath, content, requestMarkdown, contextMarkdown, relativeDir;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    repoRoot = getScheduleRepoRoot();
                    scheduleDir = node_path_1.default.join(repoRoot, '.auto_codex', 'schedule', String(options.scheduleId));
                    return [4 /*yield*/, (0, promises_1.mkdir)(scheduleDir, { recursive: true })];
                case 1:
                    _a.sent();
                    requestPath = node_path_1.default.join(scheduleDir, 'request.md');
                    contextPath = node_path_1.default.join(scheduleDir, 'context.md');
                    manifestPath = node_path_1.default.join(scheduleDir, 'manifest.json');
                    requestedPaths = extractRequestedPaths(options.note);
                    candidatePaths = __spreadArray([
                        'AGENTS.md',
                        'docs/README.md'
                    ], requestedPaths.filter(function (item) { return !item.startsWith('http://') && !item.startsWith('https://'); }), true);
                    uniqueRelativePaths = __spreadArray([], new Set(candidatePaths), true);
                    references = [];
                    _i = 0, uniqueRelativePaths_1 = uniqueRelativePaths;
                    _a.label = 2;
                case 2:
                    if (!(_i < uniqueRelativePaths_1.length)) return [3 /*break*/, 5];
                    relativePath = uniqueRelativePaths_1[_i];
                    absolutePath = node_path_1.default.resolve(repoRoot, relativePath);
                    return [4 /*yield*/, tryReadFile(absolutePath)];
                case 3:
                    content = _a.sent();
                    if (!content) {
                        return [3 /*break*/, 4];
                    }
                    references.push("## ".concat(relativePath, "\n\n```\n").concat(limitText(content), "\n```"));
                    _a.label = 4;
                case 4:
                    _i++;
                    return [3 /*break*/, 2];
                case 5:
                    requestMarkdown = [
                        '# 스케줄 요청 원문',
                        '',
                        "- \uC2A4\uCF00\uC904 ID: ".concat(options.scheduleId),
                        "- \uC791\uC5C5 ID: ".concat(options.workId),
                        '',
                        '## 원본 메모',
                        options.note.trim() || '(비어 있음)',
                    ].join('\n');
                    contextMarkdown = __spreadArray([
                        '# 스케줄 전용 참조',
                        '',
                        '- 최초 활성화 시점에 읽은 요청/문서/소스 일부를 이 디렉터리 아래로 정리했습니다.',
                        '- 이후 자동화 실행은 우선 이 디렉터리의 Markdown 문서를 참조하고, 원본 소스 재탐색은 꼭 필요할 때만 제한적으로 수행합니다.',
                        ''
                    ], (references.length > 0 ? references : ['## 참조 문서', '별도로 추출된 문서가 없습니다. request.md를 우선 참조합니다.']), true).join('\n\n');
                    return [4 /*yield*/, (0, promises_1.writeFile)(requestPath, "".concat(requestMarkdown, "\n"), 'utf8')];
                case 6:
                    _a.sent();
                    return [4 /*yield*/, (0, promises_1.writeFile)(contextPath, "".concat(contextMarkdown, "\n"), 'utf8')];
                case 7:
                    _a.sent();
                    return [4 /*yield*/, (0, promises_1.writeFile)(manifestPath, JSON.stringify({
                            scheduleId: options.scheduleId,
                            workId: options.workId,
                            refreshedAt: new Date().toISOString(),
                            forceRefresh: Boolean(options.forceRefresh),
                            sourcePaths: uniqueRelativePaths,
                        }, null, 2), 'utf8')];
                case 8:
                    _a.sent();
                    relativeDir = node_path_1.default.relative(repoRoot, scheduleDir).replace(/\\/g, '/');
                    return [2 /*return*/, {
                            directory: relativeDir,
                            requestPath: "".concat(relativeDir, "/request.md"),
                            contextPath: "".concat(relativeDir, "/context.md"),
                            manifestPath: "".concat(relativeDir, "/manifest.json"),
                        }];
            }
        });
    });
}
