// /AIWK_WEB/web_boot.js
// AIWK EXT4 v078-stage2.5-chart-lab-apex-3d-d3
(function () {
    "use strict";

    const WEB = window.AIWK_WEB = window.AIWK_WEB || {};
    WEB.version = "v078-stage2.5-chart-lab-apex-3d-d3";

    function $(id) { return document.getElementById(id); }
    function iso() { return new Date().toISOString(); }
    function safeJson(v) { try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); } }
    function line(text) {
        const out = $("aiwk-web-log");
        if (!out) { return; }
        out.textContent = "[" + new Date().toLocaleTimeString() + "] " + text + "\n" + out.textContent;
    }
    function renderExtDiag(report) {
        const out = $("aiwk-ext-diag");
        if (!out) { return; }
        out.textContent = safeJson(report || {});
    }
    function saveReceivedDiag(report) {
        try {
            const key = "AIWK_WEB_EXT4_DIAG_LOG_V042";
            const list = JSON.parse(localStorage.getItem(key) || "[]");
            list.unshift({ at: iso(), report: report || {} });
            localStorage.setItem(key, JSON.stringify(list.slice(0, 50)));
        } catch (e) {}
        try {
            fetch("api/diagnostic_log.json.php", { method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ source:"AIWK_WEB", version:WEB.version, report:report || {}, at:iso() }) }).then(function(res){ return res.json().catch(function(){ return {ok:0}; }); }).then(function(j){ line("서버 진단로그 저장 " + safeJson(j)); }).catch(function(err){ line("서버 진단로그 저장 실패 " + (err && err.message ? err.message : String(err))); });
        } catch (e) {}
    }

    function ensureWebRuntimeShim() {
        const AIWK = window.AIWK || (window.AIWK = {});
        AIWK.version = "v078-stage2.5-chart-lab-apex-3d-d3";
        AIWK.buildVersion = "0.0.78-stage2.5";
        AIWK.rootId = AIWK.rootId || "aiwk-ext4-root";
        AIWK.root = AIWK.root || {
            get: function () {
                let root = document.getElementById(AIWK.rootId || "aiwk-ext4-root");
                if (!root) {
                    root = document.createElement("div");
                    root.id = AIWK.rootId || "aiwk-ext4-root";
                    document.documentElement.appendChild(root);
                }
                root.dataset.web = "1";
                root.dataset.version = WEB.version;
                return root;
            }
        };
        try { if (AIWK.auth && typeof AIWK.auth.init === "function") AIWK.auth.init(); } catch (err) { line("WEB auth init skipped " + (err && err.message ? err.message : String(err))); }
        AIWK.comm = AIWK.comm || {};
        AIWK.comm.status = AIWK.comm.status || function () {
            const p = profile();
            return { ok: 1, kind: "AIWK_WEB_COMM_STATUS", source: "WEB1", client_id: p.client_id, group: p.group, room: p.room, address: p.group + "." + p.room + "." + p.client_id + "#web" + p.folder_route, transport: "window.postMessage/php-log", at: iso() };
        };
        AIWK.win = AIWK.win || {};
        AIWK.win.exportState = AIWK.win.exportState || function () {
            return { ok: 1, kind: "AIWK_WEB_WINDOW_STATE", source: "WEB1", windows: [], note: "WEB1 콘솔은 관찰/진단 창입니다.", at: iso() };
        };
    }

    function profile() {
        return {
            group: ($("aiwk-group") && $("aiwk-group").value) || "home",
            room: ($("aiwk-room") && $("aiwk-room").value) || "IG_CRM",
            client_id: ($("aiwk-client") && $("aiwk-client").value) || "WEB1",
            endpoint: "web",
            folder_route: ($("aiwk-folder-route") && $("aiwk-folder-route").value) || "/diagnostic/web_ext/chatGPT"
        };
    }
    function buildWebReport() {
        ensureWebRuntimeShim();
        const p = profile();
        const notes = [
            "WEB+EXT4 상호 진단 우선",
            "ChatGPT 탭에는 자동 입력까지만 하고 전송은 사용자가 직접 누름",
            "COMMON chart.demo 모듈을 WEB에서 직접 실행해 EXT 주입 문제와 모듈 문제를 분리",
            "인스타 추출 로직은 차트 template/skin 검증 후 연결"
        ];
        const extra = {
            source: "AIWK_WEB",
            profile: {
                group: p.group,
                project: p.room,
                roomId: p.room,
                clientId: p.client_id,
                folder_route: p.folder_route
            },
            web: {
                version: WEB.version,
                location: location.href,
                address: p.group + "." + p.room + "." + p.client_id + "#web" + p.folder_route,
                prompt_selector: "#prompt-textarea"
            },
            tests: [
                { id: "v077-web-console-load", title: "AIWK_WEB index.php 로딩", ok: 1, at: iso() },
                { id: "v077-chatgpt-prompt-input", title: "ChatGPT #prompt-textarea 입력 준비", ok: 0, manual: 1 },
                { id: "v077-web-ext-mutual-diagnostic", title: "WEB1 ↔ A1 상호 진단", ok: 0, manual: 1 }
            ],
            notes: notes
        };
        if (window.AIWK && AIWK.diagnostic && AIWK.diagnostic.buildReport) {
            return AIWK.diagnostic.buildReport(extra);
        }
        return Object.assign({ kind: "AIWK_CHATGPT_DIAGNOSTIC", aiwk_version: "v047", created_at: iso() }, extra);
    }
    function makeText() {
        const report = buildWebReport();
        const userText = ($("aiwk-user-text") && $("aiwk-user-text").value) || "AIWK WEB v077 COMMON 차트 크로스체크 진단 결과입니다. JSON을 분석해서 다음 최소 수정안을 제안해줘.";
        if (window.AIWK && AIWK.diagnostic && AIWK.diagnostic.toChatGptText) {
            return AIWK.diagnostic.toChatGptText(report, userText);
        }
        return userText + "\n\nAIWK_DIAG_JSON_START\n" + safeJson(report) + "\nAIWK_DIAG_JSON_END";
    }
    async function copyText(text) {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            await navigator.clipboard.writeText(text);
            return { ok: 1, method: "clipboard" };
        }
        const ta = $("aiwk-report-text");
        if (ta) { ta.focus(); ta.select(); document.execCommand("copy"); return { ok: 1, method: "execCommand" }; }
        return { ok: 0, error: "clipboard unavailable" };
    }
    function renderReport() {
        const text = makeText();
        const ta = $("aiwk-report-text");
        if (ta) { ta.value = text; }
        line("진단 결과 생성 len=" + text.length);
        return text;
    }
    function sendToChatGptTab() {
        const text = renderReport();
        window.postMessage({ type: "AIWK_WEB_CHATGPT_INSERT_REPORT", text: text }, "*");
        line("ChatGPT 탭 입력 요청 전송. 전송 버튼은 사용자가 직접 누릅니다.");
    }

    function chartStatus(text, obj) {
        const out = $("aiwk-web-chart-status");
        if (!out) { return; }
        out.textContent = String(text || "") + (obj ? "\n" + safeJson(obj) : "");
    }
    function ensureCommonChartReady() {
        ensureWebRuntimeShim();
        const AIWK = window.AIWK || {};
        if (!AIWK.root || typeof AIWK.root.get !== "function") { throw new Error("AIWK_WEB_ROOT_MISSING"); }
        if (!AIWK.modules || typeof AIWK.modules.get !== "function") { throw new Error("AIWK_MODULES_MISSING"); }
        if (!AIWK.modules.get("chart.demo")) { throw new Error("COMMON_CHART_MODULE_MISSING: chart.demo"); }
        if (!AIWK.win || typeof AIWK.win.create !== "function") { throw new Error("AIWK_WIN_CREATE_MISSING"); }
        AIWK.root.get();
        return AIWK;
    }
    function openWebChartWin(kind) {
        try {
            const AIWK = ensureCommonChartReady();
            const isViewer = kind === "viewer";
            const id = isViewer ? "web-chart-viewer-win" : "web-chart-dev-win";
            const old = AIWK.win.get && AIWK.win.get(id);
            if (old) { old.bringFront && old.bringFront(); chartStatus("기존 WEB 차트창 활성화: " + id, old.toJSON ? old.toJSON() : { id:id }); return; }
            const win = AIWK.win.create({
                id: id,
                title: (isViewer ? "WEB 차트 운영용 viewer " : "WEB 차트 개발용 template ") + WEB.version,
                shortTitle: isViewer ? "WEB차트VIEW" : "WEB차트DEV",
                icon: isViewer ? "📊" : "📈",
                module: "chart.demo",
                rect: isViewer ? { x: 720, y: 120, w: 620, h: 420 } : { x: 70, y: 120, w: 720, h: 650 }
            });
            chartStatus("WEB COMMON chart.demo 창 생성 완료: " + id, win && win.toJSON ? win.toJSON() : { id:id });
            line("WEB COMMON chart.demo 창 생성 " + id);
        } catch (err) {
            chartStatus("ERROR: " + (err && err.message ? err.message : String(err)));
            line("WEB chart open 실패 " + (err && err.message ? err.message : String(err)));
        }
    }
    async function runWebChartModule() {
        try {
            const AIWK = ensureCommonChartReady();
            let win = AIWK.win.get && (AIWK.win.get("web-chart-dev-win") || AIWK.win.get("web-chart-viewer-win"));
            if (!win) {
                openWebChartWin("dev");
                win = AIWK.win.get && AIWK.win.get("web-chart-dev-win");
            }
            if (!win) { throw new Error("WEB_CHART_WIN_CREATE_FAILED"); }
            const res = await win.run({ source:"AIWK_WEB", action:"chart.demo.run", at:iso() });
            chartStatus("chart.demo run() 결과", res);
            line("chart.demo run() OK");
        } catch (err) {
            chartStatus("ERROR: " + (err && err.message ? err.message : String(err)));
            line("chart.demo run 실패 " + (err && err.message ? err.message : String(err)));
        }
    }
    function closeWebChartWins() {
        try {
            const AIWK = window.AIWK || {};
            ["web-chart-dev-win", "web-chart-viewer-win"].forEach(function (id) {
                const win = AIWK.win && AIWK.win.get && AIWK.win.get(id);
                if (win && typeof win.close === "function") win.close();
            });
            chartStatus("WEB 차트창 닫기 요청 완료");
            line("WEB 차트창 닫기 요청");
        } catch (err) {
            chartStatus("ERROR: " + (err && err.message ? err.message : String(err)));
        }
    }

    function bind() {
        const gen = $("aiwk-btn-build-report");
        const copy = $("aiwk-btn-copy-report");
        const send = $("aiwk-btn-send-chatgpt");
        if (gen) { gen.onclick = renderReport; }
        if (copy) { copy.onclick = async function () { const r = await copyText(renderReport()); line("복사 결과 " + safeJson(r)); }; }
        if (send) { send.onclick = sendToChatGptTab; }
        const cross = $("aiwk-btn-web-cross-check");
        if (cross) { cross.onclick = function () { line("WEB 콘솔 대기 중: EXT4 popup의 home 셀프테스트를 누르면 이곳에 JSON이 표시됩니다."); renderExtDiag({ ok: 1, source: "AIWK_WEB", waiting_for: "AIWK_WEB_EXT4_DIAG_RESULT", at: iso() }); }; }
        const chartDev = $("aiwk-btn-web-chart-dev");
        const chartViewer = $("aiwk-btn-web-chart-viewer");
        const chartRun = $("aiwk-btn-web-chart-run");
        const chartClear = $("aiwk-btn-web-chart-clear");
        if (chartDev) { chartDev.onclick = function () { openWebChartWin("dev"); }; }
        if (chartViewer) { chartViewer.onclick = function () { openWebChartWin("viewer"); }; }
        if (chartRun) { chartRun.onclick = runWebChartModule; }
        if (chartClear) { chartClear.onclick = closeWebChartWins; }
        window.addEventListener("message", function (ev) {
            const msg = ev && ev.data ? ev.data : null;
            if (msg && msg.type === "AIWK_WEB_CHATGPT_INSERT_RESULT") {
                line("ChatGPT 입력 결과 " + safeJson(msg.result || {}));
            }
            if (msg && msg.type === "AIWK_WEB_EXT4_DIAG_RESULT") {
                renderExtDiag(msg.report || msg);
                saveReceivedDiag(msg.report || msg);
                line("EXT4 진단 수신 " + safeJson({ from: msg.from || "EXT4", version: msg.version || "", kind: msg.report && msg.report.kind }));
            }
        });
        ensureWebRuntimeShim();
        renderReport();
    }
    if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", bind, { once: true }); } else { bind(); }
}());
