//=============================================================================
// OntxtOUT.js
//=============================================================================

/*:
 * @plugindesc テキスト出力
 * @author Onmoremind
 * 
 *  * @help
 *  
 *  文章の表示のみを対象にしてoutputフォルダに出力
 *  
 * ========================================================
 * 【利用規約】
 *  プラグイン作者に無断で使用、改変、再配布は不可。
 */

(function () {
    const fs = require("fs");
    const path = require("path");

    function extractMessages() {
        console.log("メッセージ抽出開始...");

        const basePath = path.resolve(nw.__dirname, "output");
        if (!fs.existsSync(basePath)) {
            fs.mkdirSync(basePath);
        }

        const dataPath = path.resolve(nw.__dirname, "data");

        const systemData = JSON.parse(fs.readFileSync(path.join(dataPath, "System.json"), "utf8"));
        const mapNames = systemData.mapNames || [];

        const commonEvents = JSON.parse(fs.readFileSync(path.join(dataPath, "CommonEvents.json"), "utf8"));
        commonEvents.forEach(event => {
            if (event && event.list) {
                const messages = extractTextFromEvent(event.list);
                if (messages.length > 0) {
                    const fileName = `CE${event.id}_${sanitizeFileName(event.name || "不明")}.txt`;
                    const filePath = path.join(basePath, fileName);
                    saveMessagesToFile(filePath, messages);
                }
            }
        });

        const mapFiles = fs.readdirSync(dataPath).filter(file => file.match(/^Map([0-9]{3})\.json$/));
        mapFiles.forEach(file => {
            const mapIdMatch = file.match(/^Map([0-9]{3})\.json$/);
            const mapId = mapIdMatch ? parseInt(mapIdMatch[1], 10) : null;
            const mapData = JSON.parse(fs.readFileSync(path.join(dataPath, file), "utf8"));

            let mapName = mapId && mapNames[mapId] ? mapNames[mapId] : `マップ${mapId || "不明"}`;
            mapName = sanitizeFileName(mapName);

            if (mapData.events) {
                mapData.events.forEach(event => {
                    if (event && event.pages) {
                        let messages = [];
                        event.pages.forEach(page => {
                            messages = messages.concat(extractTextFromEvent(page.list));
                        });

                        if (messages.length > 0) {
                            const eventName = sanitizeFileName(event.name || "不明");
                            const fileName = `map${mapName}_EV${event.id}_${eventName}.txt`;
                            const filePath = path.join(basePath, fileName);
                            saveMessagesToFile(filePath, messages);
                        }
                    }
                });
            }
        });

        console.log("メッセージ一覧を output フォルダに保存しました！");
    }

    function extractTextFromEvent(eventList) {
        let messages = [];
        let currentMessage = "";

        eventList.forEach(command => {
            if (command.code === 101) {
                if (currentMessage) {
                    messages.push(currentMessage);
                }
                currentMessage = command.parameters[0];
            } else if (command.code === 401) {
                currentMessage += "\n" + command.parameters[0].replace(/^"|"$/g, '');
            } else {
                if (currentMessage) {
                    messages.push(currentMessage);
                    currentMessage = "";
                }
            }
        });

        if (currentMessage) {
            messages.push(currentMessage);
        }

        return messages;
    }

    function saveMessagesToFile(filePath, messages) {
        const content = messages.join("\n\n");
        fs.writeFileSync(filePath, content, "utf8");
    }

    function sanitizeFileName(name) {
        return name.replace(/[<>:"/\\|?*]/g, '_'); 
    }

    const _Scene_Boot_start = Scene_Boot.prototype.start;
    Scene_Boot.prototype.start = function () {
        _Scene_Boot_start.call(this);
        extractMessages();
    };
})();
