"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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.AUTOMATION_BEHAVIOR_LABELS = exports.AUTOMATION_BEHAVIOR_TYPES = void 0;
exports.normalizeAutomationTypeId = normalizeAutomationTypeId;
exports.sanitizeAutomationContexts = sanitizeAutomationContexts;
exports.upsertAutomationType = upsertAutomationType;
exports.deleteAutomationType = deleteAutomationType;
exports.resolveAutomationTypeLabel = resolveAutomationTypeLabel;
exports.buildAutomationTypeOptions = buildAutomationTypeOptions;
exports.buildAutomationContextOptions = buildAutomationContextOptions;
exports.resolveDefaultAutomationContextIds = resolveDefaultAutomationContextIds;
exports.useAutomationTypeRegistry = useAutomationTypeRegistry;
var react_1 = require("react");
var clientIdentity_1 = require("./clientIdentity");
exports.AUTOMATION_BEHAVIOR_TYPES = [
    'none',
    'plan',
    'command_execution',
    'non_source_work',
    'auto_worker',
];
var AUTOMATION_TYPES_API_PATH = '/automation-types';
var AUTOMATION_TYPE_SYNC_EVENT = 'work-app:automation-types-changed';
var AUTOMATION_TYPE_REQUEST_TIMEOUT_MS = 8000;
exports.AUTOMATION_BEHAVIOR_LABELS = {
    none: '기본유형',
    plan: '작업 요청 등록',
    command_execution: 'Command 실행',
    non_source_work: '비 소스작업',
    auto_worker: 'autoWorker',
};
var DEFAULT_AUTOMATION_TYPES = [
    {
        id: 'general-inquiry',
        name: '일반 문의',
        description: '일반 문의/확인 요청으로 처리합니다.',
        contexts: [
            {
                id: 'general-inquiry-default',
                title: '기본 확인',
                content: '소스 수정 없이 조회, 상태 확인, 응답 정리를 우선합니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'command_execution',
        enabled: true,
        updatedAt: '2026-04-29T00:00:00.000Z',
    },
    {
        id: 'none',
        name: '기본유형',
        description: '기본 자동화 처리용 유형입니다.',
        contexts: [
            {
                id: 'none-default',
                title: '기본 처리',
                content: '## 기본 처리\n- 현재 저장소 규칙과 요청 본문을 우선 따릅니다.\n- 소스 수정이 필요하면 관련 파일을 수정하고, 필요 없으면 확인 결과만 정리합니다.\n- 작업 결과에는 변경 파일, diff, preview 같은 증적을 남길 수 있습니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'none',
        enabled: true,
        updatedAt: '2026-04-23T00:00:00.000Z',
    },
    {
        id: 'plan',
        name: '작업 요청 등록',
        description: 'Plan 등록/문서형 자동화 요청으로 처리합니다.',
        contexts: [
            {
                id: 'plan-default',
                title: '문서형 처리',
                content: 'Plan 등록/문서형 요청으로 처리하고, 구현보다 등록/정리 결과를 우선 남깁니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'plan',
        enabled: true,
        updatedAt: '2026-04-23T00:00:00.000Z',
    },
    {
        id: 'command_execution',
        name: 'Command 실행',
        description: '저장소 수정 없이 명령 실행/조회 중심으로 처리합니다.',
        contexts: [
            {
                id: 'command-execution-default',
                title: '명령 실행',
                content: '저장소 수정 없이 명령 실행, API 확인, 상태 조회 중심으로 처리합니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'command_execution',
        enabled: true,
        updatedAt: '2026-04-23T00:00:00.000Z',
    },
    {
        id: 'non_source_work',
        name: '비 소스작업',
        description: '문서/운영/확인 등 비소스 작업으로 처리합니다.',
        contexts: [
            {
                id: 'non-source-work-default',
                title: '비소스 작업',
                content: '문서, 운영, 데이터 확인 등 비소스 작업으로 처리하고 코드 수정은 요청 시에만 제한적으로 수행합니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'non_source_work',
        enabled: true,
        updatedAt: '2026-04-23T00:00:00.000Z',
    },
    {
        id: 'auto_worker',
        name: 'autoWorker',
        description: '자동화 작업메모로 처리합니다.',
        contexts: [
            {
                id: 'auto-worker-default',
                title: '자동화 기본 규칙',
                content: '## context 사용 규칙\n- 자동화 실행기는 선택된 자동화 유형의 context만 우선 참조합니다.\n- Codex Live 문맥이나 일반 채팅 문맥은 자동화 기본 context로 섞지 않습니다.\n\n## 처리 원칙\n- 세부 절차는 현재 운영 설정을 따릅니다.',
                enabled: true,
                defaultSelected: true,
                updatedAt: '2026-04-29T00:00:00.000Z',
            },
        ],
        behaviorType: 'auto_worker',
        enabled: true,
        updatedAt: '2026-04-23T00:00:00.000Z',
    },
];
function normalizeText(value) {
    var _a;
    return (_a = value === null || value === void 0 ? void 0 : value.trim()) !== null && _a !== void 0 ? _a : '';
}
function normalizeAutomationTypeId(value) {
    var normalized = normalizeText(typeof value === 'string' ? value : '');
    if (normalized === 'stock-alert') {
        return 'general-inquiry';
    }
    if (normalized === 'plan_registration') {
        return 'plan';
    }
    if (normalized === 'general_development') {
        return 'auto_worker';
    }
    return normalized || 'none';
}
function normalizeBehaviorType(value) {
    var normalized = normalizeAutomationTypeId(value);
    return exports.AUTOMATION_BEHAVIOR_TYPES.includes(normalized)
        ? normalized
        : 'none';
}
function getSemanticKey(record) {
    return "".concat(record.behaviorType, ":").concat(normalizeText(record.name).replace(/\s+/g, ' ').toLocaleLowerCase('ko-KR'));
}
function compareUpdatedAt(left, right) {
    var leftTime = Date.parse(left.updatedAt);
    var rightTime = Date.parse(right.updatedAt);
    if (Number.isFinite(leftTime) && Number.isFinite(rightTime) && leftTime !== rightTime) {
        return leftTime - rightTime;
    }
    return 0;
}
function compareContextUpdatedAt(left, right) {
    var leftTime = Date.parse(left.updatedAt);
    var rightTime = Date.parse(right.updatedAt);
    if (Number.isFinite(leftTime) && Number.isFinite(rightTime) && leftTime !== rightTime) {
        return leftTime - rightTime;
    }
    return 0;
}
function normalizeAutomationContext(record) {
    var title = normalizeText(record.title);
    var content = normalizeText(record.content);
    if (!title && !content) {
        return null;
    }
    var id = normalizeText(record.id) ||
        "automation-context-".concat(Date.now().toString(36), "-").concat(Math.random().toString(36).slice(2, 8));
    return {
        id: id,
        title: title || 'Context',
        content: content,
        enabled: record.enabled !== false,
        defaultSelected: record.defaultSelected !== false,
        updatedAt: normalizeText(record.updatedAt) || new Date().toISOString(),
    };
}
function sanitizeAutomationContexts(items) {
    var byId = new Map();
    var bySemanticKey = new Map();
    (items !== null && items !== void 0 ? items : [])
        .map(function (item) { return normalizeAutomationContext(item); })
        .filter(function (item) { return Boolean(item); })
        .forEach(function (item) {
        var currentById = byId.get(item.id);
        if (!currentById || compareContextUpdatedAt(currentById, item) <= 0) {
            byId.set(item.id, item);
        }
    });
    for (var _i = 0, _a = byId.values(); _i < _a.length; _i++) {
        var item = _a[_i];
        var semanticKey = normalizeText(item.title).replace(/\s+/g, ' ').toLocaleLowerCase('ko-KR');
        var current = bySemanticKey.get(semanticKey);
        if (!current || compareContextUpdatedAt(current, item) <= 0) {
            bySemanticKey.set(semanticKey, item);
        }
    }
    return Array.from(bySemanticKey.values()).sort(function (left, right) { return left.title.localeCompare(right.title, 'ko-KR'); });
}
function normalizeAutomationType(record) {
    var name = normalizeText(record.name);
    if (!name) {
        return null;
    }
    var id = normalizeText(record.id) ||
        "automation-type-".concat(Date.now().toString(36), "-").concat(Math.random().toString(36).slice(2, 8));
    return {
        id: id,
        name: name,
        description: normalizeText(record.description),
        contexts: sanitizeAutomationContexts(record.contexts),
        behaviorType: normalizeBehaviorType(record.behaviorType),
        enabled: record.enabled !== false,
        updatedAt: normalizeText(record.updatedAt) || new Date().toISOString(),
    };
}
function sanitizeAutomationTypes(items) {
    var byId = new Map();
    var bySemanticKey = new Map();
    items
        .map(function (item) { return normalizeAutomationType(item); })
        .filter(function (item) { return Boolean(item); })
        .forEach(function (item) {
        var currentById = byId.get(item.id);
        if (!currentById || compareUpdatedAt(currentById, item) <= 0) {
            byId.set(item.id, item);
        }
    });
    for (var _i = 0, _a = byId.values(); _i < _a.length; _i++) {
        var item = _a[_i];
        var semanticKey = getSemanticKey(item);
        var current = bySemanticKey.get(semanticKey);
        if (!current || compareUpdatedAt(current, item) <= 0) {
            bySemanticKey.set(semanticKey, item);
        }
    }
    var values = Array.from(bySemanticKey.values()).sort(function (left, right) { return left.name.localeCompare(right.name, 'ko-KR'); });
    return values.length > 0 ? values : DEFAULT_AUTOMATION_TYPES;
}
function emitAutomationTypesChange() {
    if (typeof window === 'undefined') {
        return;
    }
    window.dispatchEvent(new Event(AUTOMATION_TYPE_SYNC_EVENT));
}
function resolveApiBaseUrl() {
    if (import.meta.env.VITE_WORK_SERVER_URL) {
        return import.meta.env.VITE_WORK_SERVER_URL;
    }
    return '/api';
}
function resolveFallbackBaseUrl() {
    if (typeof window === 'undefined') {
        return null;
    }
    var hostname = window.location.hostname;
    if (!['localhost', '127.0.0.1', '0.0.0.0'].includes(hostname)) {
        return null;
    }
    var fallbackUrl = new URL(window.location.origin);
    fallbackUrl.port = '3100';
    fallbackUrl.pathname = '/api';
    fallbackUrl.search = '';
    fallbackUrl.hash = '';
    return fallbackUrl.toString().replace(/\/+$/, '');
}
var API_BASE_URL = resolveApiBaseUrl();
var FALLBACK_BASE_URL = resolveFallbackBaseUrl();
function requestOnce(baseUrl, init) {
    return __awaiter(this, void 0, void 0, function () {
        var headers, hasBody, controller, timeoutId, response, _a;
        var _b, _c;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    headers = (0, clientIdentity_1.appendClientIdHeader)(init === null || init === void 0 ? void 0 : init.headers);
                    hasBody = (init === null || init === void 0 ? void 0 : init.body) !== undefined && (init === null || init === void 0 ? void 0 : init.body) !== null;
                    controller = new AbortController();
                    timeoutId = window.setTimeout(function () { return controller.abort(); }, AUTOMATION_TYPE_REQUEST_TIMEOUT_MS);
                    if (hasBody && !headers.has('Content-Type')) {
                        headers.set('Content-Type', 'application/json');
                    }
                    _d.label = 1;
                case 1:
                    _d.trys.push([1, , 5, 6]);
                    return [4 /*yield*/, fetch("".concat(baseUrl).concat(AUTOMATION_TYPES_API_PATH), __assign(__assign({}, init), { headers: headers, signal: controller.signal, cache: (_b = init === null || init === void 0 ? void 0 : init.cache) !== null && _b !== void 0 ? _b : (((_c = init === null || init === void 0 ? void 0 : init.method) === null || _c === void 0 ? void 0 : _c.toUpperCase()) === 'GET' ? 'no-store' : undefined) }))];
                case 2:
                    response = _d.sent();
                    if (!!response.ok) return [3 /*break*/, 4];
                    _a = Error.bind;
                    return [4 /*yield*/, response.text()];
                case 3: throw new (_a.apply(Error, [void 0, (_d.sent()) || '자동화 처리 유형 요청에 실패했습니다.']))();
                case 4: return [2 /*return*/, response.json()];
                case 5:
                    window.clearTimeout(timeoutId);
                    return [7 /*endfinally*/];
                case 6: return [2 /*return*/];
            }
        });
    });
}
function requestAutomationTypes(init) {
    return __awaiter(this, void 0, void 0, function () {
        var error_1, shouldRetryWithFallback;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, requestOnce(API_BASE_URL, init)];
                case 1: return [2 /*return*/, _a.sent()];
                case 2:
                    error_1 = _a.sent();
                    shouldRetryWithFallback = FALLBACK_BASE_URL &&
                        FALLBACK_BASE_URL !== API_BASE_URL &&
                        error_1 instanceof Error &&
                        /404|408|502|Failed to fetch|Load failed|NetworkError|응답이 지연/i.test(error_1.message);
                    if (!shouldRetryWithFallback) {
                        throw error_1;
                    }
                    return [2 /*return*/, requestOnce(FALLBACK_BASE_URL, init)];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function loadAutomationTypesFromServer() {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, requestAutomationTypes({
                        method: 'GET',
                    })];
                case 1:
                    response = _a.sent();
                    if (response.automationTypes == null) {
                        return [2 /*return*/, DEFAULT_AUTOMATION_TYPES];
                    }
                    return [2 /*return*/, sanitizeAutomationTypes(response.automationTypes)];
            }
        });
    });
}
function saveAutomationTypesToServer(items) {
    return __awaiter(this, void 0, void 0, function () {
        var resolved, response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    resolved = sanitizeAutomationTypes(items);
                    return [4 /*yield*/, requestAutomationTypes({
                            method: 'PUT',
                            body: JSON.stringify({ automationTypes: resolved }),
                        })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, sanitizeAutomationTypes(response.automationTypes)];
            }
        });
    });
}
function upsertAutomationType(items, input) {
    var nextItem = normalizeAutomationType(input);
    if (!nextItem) {
        return sanitizeAutomationTypes(items);
    }
    var nextItems = items.filter(function (item) { return item.id !== nextItem.id; });
    nextItems.push(nextItem);
    return sanitizeAutomationTypes(nextItems);
}
function deleteAutomationType(items, automationTypeId) {
    var normalizedId = normalizeText(automationTypeId);
    if (!normalizedId) {
        return sanitizeAutomationTypes(items);
    }
    return sanitizeAutomationTypes(items.filter(function (item) { return item.id !== normalizedId; }));
}
function resolveAutomationTypeLabel(items, automationTypeId) {
    var _a, _b;
    var normalizedId = normalizeAutomationTypeId(automationTypeId);
    return (_b = (_a = items.find(function (item) { return item.id === normalizedId; })) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : normalizedId;
}
function buildAutomationTypeOptions(items, value) {
    var normalizedValue = normalizeAutomationTypeId(value);
    var enabledItems = items.filter(function (item) { return item.enabled; });
    var currentItem = items.find(function (item) { return item.id === normalizedValue; });
    var source = currentItem && !enabledItems.some(function (item) { return item.id === currentItem.id; }) ? __spreadArray(__spreadArray([], enabledItems, true), [currentItem], false) : enabledItems;
    if (source.length === 0) {
        return [{ label: '선택 안함', value: 'none' }];
    }
    return source.map(function (item) { return ({
        label: item.name,
        value: item.id,
    }); });
}
function buildAutomationContextOptions(items, automationTypeId, selectedContextIds) {
    var _a;
    if (selectedContextIds === void 0) { selectedContextIds = []; }
    var normalizedId = normalizeAutomationTypeId(automationTypeId);
    var automationType = (_a = items.find(function (item) { return item.id === normalizedId; })) !== null && _a !== void 0 ? _a : null;
    var contexts = sanitizeAutomationContexts(automationType === null || automationType === void 0 ? void 0 : automationType.contexts);
    var selectedSet = new Set(selectedContextIds);
    var enabledIds = new Set(contexts.filter(function (item) { return item.enabled; }).map(function (item) { return item.id; }));
    return contexts
        .filter(function (item) { return enabledIds.has(item.id) || selectedSet.has(item.id); })
        .map(function (item) { return ({
        label: item.title,
        value: item.id,
    }); });
}
function resolveDefaultAutomationContextIds(items, automationTypeId) {
    var _a;
    var normalizedId = normalizeAutomationTypeId(automationTypeId);
    var automationType = (_a = items.find(function (item) { return item.id === normalizedId; })) !== null && _a !== void 0 ? _a : null;
    return sanitizeAutomationContexts(automationType === null || automationType === void 0 ? void 0 : automationType.contexts)
        .filter(function (item) { return item.enabled && item.defaultSelected; })
        .map(function (item) { return item.id; });
}
function useAutomationTypeRegistry() {
    var _this = this;
    var _a = (0, react_1.useState)(DEFAULT_AUTOMATION_TYPES), automationTypes = _a[0], setAutomationTypesState = _a[1];
    var _b = (0, react_1.useState)(true), isLoading = _b[0], setIsLoading = _b[1];
    var _c = (0, react_1.useState)(''), errorMessage = _c[0], setErrorMessage = _c[1];
    var mountedRef = (0, react_1.useRef)(true);
    (0, react_1.useEffect)(function () {
        mountedRef.current = true;
        return function () {
            mountedRef.current = false;
        };
    }, []);
    (0, react_1.useEffect)(function () {
        var cancelled = false;
        var load = function () { return __awaiter(_this, void 0, void 0, function () {
            var nextAutomationTypes, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        setIsLoading(true);
                        setErrorMessage('');
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, 4, 5]);
                        return [4 /*yield*/, loadAutomationTypesFromServer()];
                    case 2:
                        nextAutomationTypes = _a.sent();
                        if (!cancelled && mountedRef.current) {
                            setAutomationTypesState(nextAutomationTypes);
                        }
                        return [3 /*break*/, 5];
                    case 3:
                        error_2 = _a.sent();
                        if (!cancelled && mountedRef.current) {
                            setAutomationTypesState(DEFAULT_AUTOMATION_TYPES);
                            setErrorMessage(error_2 instanceof Error ? error_2.message : '자동화 처리 유형을 불러오지 못했습니다.');
                        }
                        return [3 /*break*/, 5];
                    case 4:
                        if (!cancelled && mountedRef.current) {
                            setIsLoading(false);
                        }
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        }); };
        void load();
        var handleSync = function () {
            void load();
        };
        window.addEventListener(AUTOMATION_TYPE_SYNC_EVENT, handleSync);
        return function () {
            cancelled = true;
            window.removeEventListener(AUTOMATION_TYPE_SYNC_EVENT, handleSync);
        };
    }, []);
    var setAutomationTypes = function (nextItems) { return __awaiter(_this, void 0, void 0, function () {
        var saved;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, saveAutomationTypesToServer(nextItems)];
                case 1:
                    saved = _a.sent();
                    if (mountedRef.current) {
                        setAutomationTypesState(saved);
                        setErrorMessage('');
                    }
                    emitAutomationTypesChange();
                    return [2 /*return*/, saved];
            }
        });
    }); };
    return {
        automationTypes: automationTypes,
        setAutomationTypes: setAutomationTypes,
        isLoading: isLoading,
        errorMessage: errorMessage,
    };
}
