"use strict";
const path = require('path');
const fs = require("fs");

const scenarioNum = 518320;
const outDir = `F:\\scenario_${scenarioNum}`;

const startNum = 1, endNum = 20;
const suffix = "cyov4";

if (!fs.existsSync(outDir)) fs.mkdirSync(outDir);
else if (!fs.statSync(outDir).isDirectory()) throw new Error(`path [${outDir}] exists`);

const fetchAll = async () => {
    for (let i = startNum; i <= endNum; i++) {
        console.log(`${scenarioNum} ${i}/${endNum}`);
        console.log(`fetching`);
        let resp = await fetch(`https://android.magi-reco.com/magica/resource/download/asset/master/resource/scenario/json/adv/`
            + `scenario_5/${scenarioNum}-${i}_${suffix}.json`);
        if (!resp.ok) throw new Error(`request ${i} is not ok`);
        let contentType = resp.headers.get("Content-Type");
        if (!contentType.match(/^(text|application)\/json/i)) throw new Error(`content type of ${i} is ${contentType}`);
        let text = await resp.text();
        let json = JSON.parse(text);

        console.log(`converting`);
        let scenario = json.story.group_1.map(d => {
            let type = ["narration", "textLeft", "textCenter", "textRight"].find(t => d[t] != null);
            if (type == null) return "";
            let nameKey = type.replace("text", "name").replace(/^narration$/, "nameNarration");
            let name = nameKey === "nameNarration" && d[nameKey] === "" ? "ナレーター" : d[nameKey] == null ? "(続き)" : d[nameKey];
            return `${name}: ${d[type].replaceAll("@", "")}\n\n`;
        }).join("");

        console.log(`writing`);
        fs.writeFileSync(path.join(outDir, `${i}.txt`), scenario);

        console.log(`done\n`);
    }
}

fetchAll();