'use strict';

const fs = require('fs');
const path = require('path');

async function findComp(nodeUuid, typeNames) {
    if (!nodeUuid || typeof Editor === 'undefined') return null;
    const node = await Editor.Message.request('scene', 'query-node', nodeUuid);
    const comps = node?.__comps__ || [];
    for (const c of comps) {
        if (typeNames.indexOf(c.type) >= 0) {
            return c.value.uuid.value;
        }
    }
    return null;
}

async function callOnNode(nodeUuid, typeNames, method, args) {
    try {
        const uuid = await findComp(nodeUuid, typeNames);
        if (!uuid) {
            console.warn('[game-controller-inspector] 选中节点上未找到', typeNames.join('/'));
            return;
        }
        await Editor.Message.request('scene', 'execute-component-method', {
            uuid,
            name: method,
            args: args || [],
        });
    } catch (e) {
        console.warn('[game-controller-inspector]', method, e);
    }
}

const BOOTSTRAP_TYPES = ['AppBootstrap', 'c0468XFPX1InLN14gtZ5PLf'];
const GAME_TYPES = ['GameController'];

function readLevelDatabaseJson() {
    if (typeof Editor === 'undefined' || !Editor.Project?.path) return null;
    const dbPath = path.join(Editor.Project.path, 'assets', 'level-data', 'levels-database.json');
    if (!fs.existsSync(dbPath)) {
        console.warn('[game-controller-inspector] 未找到 assets/level-data/levels-database.json');
        return null;
    }
    try {
        return JSON.parse(fs.readFileSync(dbPath, 'utf8'));
    } catch (e) {
        console.warn('[game-controller-inspector] 解析关卡库失败', e);
        return null;
    }
}

/** 编辑器 ▶ 预览：注入关卡库（不再打包进 resources bundle） */
function installPreviewLevelDbHook() {
    if (typeof Editor === 'undefined' || !Editor.Message?.addBroadcastListener) return;
    Editor.Message.addBroadcastListener('scene:ready-for-preview', () => {
        const json = readLevelDatabaseJson();
        if (!json) return;
        Editor.Message.request('scene', 'execute-scene-script', {
            name: 'game-controller-inspector',
            method: 'apply',
            args: [json],
        }).catch((e) => {
            console.warn('[game-controller-inspector] 预览注入关卡库失败，请通过 scratch-gui 嵌入测试', e);
        });
    });
}

exports.load = function load() {
    console.log('[game-controller-inspector] v3.4 — AppBootstrap 面板含游戏调试');
    installPreviewLevelDbHook();
};

exports.unload = function unload() {
    console.log('[game-controller-inspector] 已卸载');
};

async function callGameOnSelection(method, args) {
    const uuids = Editor.Selection.getSelected('node');
    if (!uuids || !uuids.length) {
        console.warn('[game-controller-inspector] 请先在层级管理器选中含 GameController 的节点');
        return;
    }
    await callOnNode(uuids[0], GAME_TYPES, method, args);
}

exports.methods = {
    async switchLevelOnSelection() {
        const uuids = Editor.Selection.getSelected('node');
        if (!uuids || !uuids.length) {
            console.warn('[game-controller-inspector] 请先在层级管理器选中 AppRoot');
            return;
        }
        await callOnNode(uuids[0], BOOTSTRAP_TYPES, 'switchLevelFromBootstrap', []);
    },
    async debugMoveOnSelection() {
        await callGameOnSelection('debugMove', [1]);
    },
    async debugJumpOnSelection() {
        await callGameOnSelection('debugJump', []);
    },
    async debugPlayerInfoOnSelection() {
        await callGameOnSelection('debugPlayerInfo', []);
    },
};
