// /AIWK_COMMON/core/yw-route.js
// AIWK EXT4 v037
(function () {
    "use strict";

    const AIWK = window.AIWK;
    if (!AIWK) {
        throw new Error("yw-route stopped: AIWK is missing. 해결: aiwk_core.js를 먼저 로드하십시오.");
    }

    function cleanPart(v, fallback) {
        const s = String(v || "").trim();
        return s || String(fallback || "").trim();
    }

    function normalizeRoutePart(v) {
        return cleanPart(v, "_").replace(/^\/+|\/+$/g, "");
    }

    function buildAddress(o) {
        o = o || {};
        const group = cleanPart(o.group || o.net, "home");
        const room = cleanPart(o.room, "prj_default");
        const clientId = cleanPart(o.client_id || o.clientId, "C1");
        const endpoint = cleanPart(o.endpoint, "cmd");
        const project = normalizeRoutePart(o.project || o.project_id || "default");
        const stage1 = normalizeRoutePart(o.stage1 || o.stage1_id || "st1_default");
        const stage2 = normalizeRoutePart(o.stage2 || o.stage2_id || "st2_default");
        const win = normalizeRoutePart(o.win || o.win_id || "win_default");
        const port = normalizeRoutePart(o.port || o.action || "run");
        return group + "." + room + "." + clientId + "#" + endpoint + "/" + [project, stage1, stage2, win, port].join("/");
    }

    function parseAddress(address) {
        const src = String(address || "").trim();
        const out = { raw: src, ok: 0 };
        const hashAt = src.indexOf("#");
        const head = hashAt >= 0 ? src.slice(0, hashAt) : src;
        const tail = hashAt >= 0 ? src.slice(hashAt + 1) : "";
        const h = head.split(".");
        out.group = h[0] || "";
        out.net = out.group;
        out.room = h[1] || "";
        out.client_id = h[2] || "";
        const slashAt = tail.indexOf("/");
        out.endpoint = slashAt >= 0 ? tail.slice(0, slashAt) : tail;
        out.route = slashAt >= 0 ? tail.slice(slashAt) : "";
        const r = out.route.replace(/^\//, "").split("/");
        out.project_id = r[0] || "";
        out.stage1_id = r[1] || "";
        out.stage2_id = r[2] || "";
        out.win_id = r[3] || "";
        out.port = r[4] || "";
        out.ok = out.group && out.room && out.client_id ? 1 : 0;
        out.folder_route = out.route;
        return out;
    }

    AIWK.route = {
        buildAddress: buildAddress,
        parseAddress: parseAddress,
        format: "group.room.client_id#endpoint/folder_route/win/port",
        wssScope: "group.room.client_id",
        folderRoute: "route 뒤쪽 /project/stage1/stage2/win/port 는 실제 파일 폴더가 아니라 폴더처럼 묶는 논리 경로"
    };
}());
