// /AIWK_COMMON/modules/site/profile_registry.js
// AIWK EXT4 v015
(function () {
    "use strict";

    const AIWK = window.AIWK;

    function el(tag, className, text) {
        const node = document.createElement(tag);
        if (className) {
            node.className = className;
        }
        if (text !== undefined) {
            node.textContent = text;
        }
        return node;
    }

    function json(obj) {
        return JSON.stringify(obj, null, 2);
    }

    function makePrint(status, testId, name, result, detail, extra) {
        const lines = [
            "PRINT: " + status,
            "TEST: " + testId,
            "NAME: " + name,
            "RESULT: " + result
        ];
        if (detail) {
            lines.push("DETAIL: " + detail);
        }
        if (extra) {
            Object.keys(extra).forEach(function (key) {
                const val = extra[key];
                if (typeof val === "object") {
                    lines.push(key + ": " + json(val));
                } else {
                    lines.push(key + ": " + String(val));
                }
            });
        }
        return lines.join("\n");
    }

    function printOk(testId, name, detail, extra) {
        return makePrint("정상", testId, name, "OK", detail, Object.assign({ NEXT: "계속 진행 가능" }, extra || {}));
    }

    function printError(testId, name, code, cause, fix, extra) {
        return makePrint("오류", testId, name, "ERROR", cause, Object.assign({ ERROR_CODE: code, FIX: fix, STOP: true }, extra || {}));
    }

    AIWK.modules.register("site.profile_registry", {
        name: "site.profile_registry",
        run: async function (ctx) {
            const info = AIWK.siteProfile.currentInfo();
            AIWK.siteProfile.loadForHost(info.hostname);
            return {
                ok: 1,
                module: "site.profile_registry",
                win_id: ctx.win.id,
                role: AIWK.auth.role,
                current: info,
                storage_key: AIWK.siteProfile.storageKey(info.hostname),
                profiles: AIWK.siteProfile.list(),
                received: ctx.msg || {},
                message: "site.profile_registry run completed"
            };
        },
        test: async function (ctx) {
            if (!AIWK.auth.can("dev")) {
                return {
                    ok: 0,
                    module: "site.profile_registry",
                    win_id: ctx.win.id,
                    role: AIWK.auth.role,
                    code: "DEV_ROLE_REQUIRED",
                    message: "dev 권한이 필요합니다. Token Login 후 다시 TEST 하십시오."
                };
            }
            const result = AIWK.siteProfile.testRegisterCurrentSite();
            return {
                ok: 1,
                module: "site.profile_registry",
                win_id: ctx.win.id,
                role: AIWK.auth.role,
                result: result,
                message: "site.profile_registry test completed"
            };
        },
        mount: function (ctx) {
            const box = el("div", "space-y-2 text-sm aiwk-site-profile select-text");
            const title = el("div", "text-base font-semibold select-text", "Site Profile 등록 v015");
            const desc = el("div", "text-xs select-text", "현재 도메인 기준 Site Profile을 dev 권한으로 저장/불러오기 검증합니다.");
            const actions = el("div", "flex flex-wrap gap-1 select-text");
            const resultBox = el("pre", "aiwk-run-result select-text", "버튼을 눌러 Site Profile을 검증하십시오.");
            const msgBox = el("div", "aiwk-auth-msg select-text", "");
            const edit = document.createElement("textarea");
            edit.className = "aiwk-textarea w-full px-2 py-1 rounded border select-text";
            edit.rows = 7;
            edit.setAttribute("data-aiwk-textarea-key", "site_profile_json");

            function btn(label, action, needRole) {
                const b = document.createElement("button");
                b.type = "button";
                b.className = "aiwk-btn";
                b.dataset.siteAction = action;
                b.dataset.needRole = needRole || "guest";
                b.textContent = label;
                return b;
            }

            actions.appendChild(btn("현재 사이트", "current", "guest"));
            actions.appendChild(btn("기본 Profile 생성", "build", "guest"));
            actions.appendChild(btn("Profile 저장(dev)", "save", "dev"));
            actions.appendChild(btn("저장/불러오기 TEST(dev)", "save_load_test", "dev"));
            actions.appendChild(btn("저장 목록", "list", "guest"));
            actions.appendChild(btn("현재 도메인 삭제(dev)", "remove", "dev"));
            actions.appendChild(btn("권한 오류 TEST", "expected_auth_error", "guest"));

            function refreshAuthButtons() {
                actions.querySelectorAll("button[data-need-role]").forEach(function (b) {
                    if (AIWK.winRender && typeof AIWK.winRender.applyAuthToButton === "function") {
                        AIWK.winRender.applyAuthToButton(b);
                    }
                });
            }

            function setPrint(text, ok) {
                resultBox.textContent = text;
                msgBox.textContent = ok ? "SUCCESS" : "STOPPED";
                msgBox.className = ok ? "aiwk-auth-msg aiwk-ok select-text" : "aiwk-auth-msg aiwk-err select-text";
                ctx.status.textContent = ok ? "success" : "stopped";
            }

            function runAction(action, needRole) {
                const info = AIWK.siteProfile.currentInfo();
                if (needRole && !AIWK.auth.can(needRole)) {
                    throw new Error("AUTH_REQUIRED: " + action + " requires " + needRole + ". 해결: Token Login으로 dev 권한을 얻으십시오.");
                }
                if (action === "current") {
                    return { ok: 1, current: info, role: AIWK.auth.role, storage_key: AIWK.siteProfile.storageKey(info.hostname) };
                }
                if (action === "build") {
                    const profile = AIWK.siteProfile.buildDefaultForCurrentSite();
                    edit.value = json(profile);
                    return { ok: 1, built: profile };
                }
                if (action === "save") {
                    const profile = JSON.parse(edit.value || "{}");
                    const saved = AIWK.siteProfile.save(profile);
                    return { ok: 1, saved: saved, profiles: AIWK.siteProfile.list() };
                }
                if (action === "save_load_test") {
                    const res = AIWK.siteProfile.testRegisterCurrentSite();
                    edit.value = json(res.saved);
                    return res;
                }
                if (action === "list") {
                    const loaded = AIWK.siteProfile.loadForHost(info.hostname);
                    return { ok: 1, loaded: loaded, profiles: AIWK.siteProfile.list(), role: AIWK.auth.role };
                }
                if (action === "remove") {
                    const removed = AIWK.siteProfile.removeForHost(info.hostname);
                    return { ok: 1, removed: removed, profiles: AIWK.siteProfile.list() };
                }
                if (action === "expected_auth_error") {
                    const savedRole = AIWK.auth.role;
                    if (AIWK.auth.can("dev")) {
                        return { ok: 1, expected: "dev already authorized", role: savedRole, message: "dev 상태에서는 AUTH_REQUIRED가 발생하지 않습니다." };
                    }
                    try {
                        AIWK.siteProfile.saveDefaultForCurrentSite();
                        throw new Error("EXPECTED_AUTH_ERROR_NOT_RAISED: guest/editor 상태에서 저장이 막히지 않았습니다.");
                    } catch (errExpected) {
                        return { ok: 1, expected_error: errExpected.message, message: "권한 오류가 화면 결과로만 검증되었습니다." };
                    }
                }
                throw new Error("UNKNOWN_SITE_ACTION: " + action);
            }

            actions.addEventListener("click", function (ev) {
                const b = ev.target.closest("button[data-site-action]");
                if (!b) {
                    return;
                }
                ev.preventDefault();
                ev.stopPropagation();
                const action = b.dataset.siteAction;
                const needRole = b.dataset.needRole || "guest";
                try {
                    const res = runAction(action, needRole === "guest" ? "guest" : needRole);
                    setPrint(printOk("site-profile-" + action, action, "Site Profile action completed", { RESULT_JSON: res }), true);
                } catch (err) {
                    setPrint(printError("site-profile-" + action, action, "SITE_PROFILE_ACTION_FAIL", err.message, "dev 토큰, JSON 형식, profile_id/site.domain/url_rules/targets, 저장소 key를 확인하십시오."), false);
                }
            });

            AIWK.events.on("auth:change", refreshAuthButtons);
            const checks = el("div", "aiwk-checkbox select-text", "");
            checks.innerHTML = "<b>v015 검토 항목</b><br>" +
                "1. TEST 버튼 또는 저장/불러오기 TEST(dev) 클릭 → PRINT: 정상 확인<br>" +
                "2. Profile 저장(dev) → 현재 도메인 profile 저장 확인<br>" +
                "3. 저장 목록 → loaded/profile 표시 확인<br>" +
                "4. dev가 아니면 저장은 PRINT: 오류 + 해결 메시지 확인<br>" +
                "5. 모든 텍스트 드래그 선택/복사 가능 확인";

            box.appendChild(title);
            box.appendChild(desc);
            box.appendChild(actions);
            box.appendChild(msgBox);
            box.appendChild(edit);
            box.appendChild(resultBox);
            box.appendChild(checks);
            ctx.body.appendChild(box);
            refreshAuthButtons();
            ctx.status.textContent = "v015 site profile ready";
        }
    });
}());
