// /AIWK_COMMON/modules/comm/bus_test.js
// AIWK EXT4 v027 · BUS 통신 테스트창: 상태등/로그 제어
(function () {
    "use strict";

    const AIWK = window.AIWK;
    function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; }
    function pretty(v) { try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); } }
    function nowIso(){ return new Date().toISOString(); }
    function makeBtn(label, fn, extra) { const b = document.createElement("button"); b.type = "button"; b.className = "aiwk-btn" + (extra ? " " + extra : ""); b.textContent = label; b.onclick = fn; return b; }
    function makeLogTools(out) { const line=el("div","aiwk-comm-logline",""); const ck=document.createElement("input"); ck.type="checkbox"; ck.checked=AIWK.comm?AIWK.comm.getLogEnabled():true; const label=document.createElement("label"); label.appendChild(ck); label.appendChild(document.createTextNode(" 로그")); const trash=makeBtn("🗑",function(){out.textContent="";},"aiwk-comm-trash"); trash.title="로그 삭제"; ck.onchange=function(){ if(AIWK.comm) AIWK.comm.setLogEnabled(ck.checked); }; line.appendChild(label); line.appendChild(trash); line.appendChild(el("span","select-text","5000줄 초과 시 자동 정리")); return {line:line, checkbox:ck}; }
    function logTo(out, title, obj) { if (AIWK.comm) AIWK.comm.appendToBox(out, title, obj, AIWK.comm.getLogEnabled(), 5000); }

    AIWK.modules.register("comm.bus_test", {
        name: "comm.bus_test",
        run: async function(ctx) { return { ok: 1, module: "comm.bus_test", win_id: ctx.win.id, status: AIWK.comm ? AIWK.comm.status() : {}, received: ctx.msg || {}, message: "BUS test window run completed" }; },
        mount: function(ctx) {
            const box = el("div", "space-y-2 text-sm select-text");
            const title = el("div", "text-base font-semibold", "BUS 통신 테스트창 v027");
            const desc = el("div", "text-xs", "Window BUS와 Tab BUS를 분리해서 테스트합니다. Tab BUS는 같은 Chrome 안 다른 탭으로 보냅니다.");
            const statusBar = el("div", "aiwk-comm-status-row", "");
            const status = el("pre", "aiwk-auth-payload select-text", "");
            const row = el("div", "aiwk-comm-toolbar", "");
            const target = document.createElement("input"); target.className = "aiwk-input"; target.value = "A*#tabbus"; target.placeholder = "대상 예: A2#tabbus / A*#tabbus";
            const action = document.createElement("input"); action.className = "aiwk-input"; action.value = "tabbus.test"; action.placeholder = "action";
            const payload = document.createElement("textarea"); payload.className = "aiwk-input"; payload.setAttribute("data-aiwk-textarea-key", "bus_payload"); payload.value = JSON.stringify({ text: "Tab BUS 테스트", at: nowIso() }, null, 2);
            const out = el("pre", "aiwk-run-result select-text", "");
            const logTools = makeLogTools(out);
            function refresh() { const s=AIWK.comm ? AIWK.comm.status() : { error: "AIWK.comm missing" }; status.textContent = pretty(s); if(AIWK.comm) AIWK.comm.renderStatusBar(statusBar); ctx.status.textContent = "BUS 상태: " + ((s.indicators && s.indicators.bus && s.indicators.bus.text) || "?") + " / " + (s.indicator_text || ""); }
            row.appendChild(makeBtn("상태 갱신", refresh));
            row.appendChild(makeBtn("Tab BUS 등록", async function(){ const r = await AIWK.comm.tabRegister("tabbus"); logTo(out,"Tab BUS 등록",r); refresh(); }));
            row.appendChild(makeBtn("같은 챗방 목록", async function(){ const r = await AIWK.comm.tabList(); logTo(out,"Tab BUS 목록",r); refresh(); }));
            row.appendChild(makeBtn("Tab BUS 전송", async function(){ let p={}; try{p=JSON.parse(payload.value||"{}");}catch(e){p={raw:payload.value};} const r=await AIWK.comm.tabSend(target.value, action.value, p, "tabbus"); logTo(out,"Tab BUS 전송",r); refresh(); }));
            row.appendChild(makeBtn("Window BUS selftest", async function(){ const r = window.AIWK_BUS ? await window.AIWK_BUS.ask("bus-test-win", "셀프테스트 해라!", { source:"comm.bus_test", at:nowIso() }) : { ok:0, error:"AIWK_BUS missing" }; logTo(out,"Window BUS selftest",r); refresh(); }));
            box.appendChild(title); box.appendChild(desc); box.appendChild(statusBar); box.appendChild(status); box.appendChild(row); box.appendChild(target); box.appendChild(action); box.appendChild(payload); box.appendChild(logTools.line); box.appendChild(out);
            ctx.body.appendChild(box); refresh();
            AIWK.events.on("comm:status", refresh);
            AIWK.events.on("comm:tab:message", function(packet){ logTo(out,"Tab BUS 수신",packet); refresh(); });
        }
    });
}());
