// 离线分析脚本（不属于游戏，删 _analysis 目录即可移除）
// 复用引擎真正的 getDamageInfo，计算 WildArea 各怪在「所有配招 × 携带物」下的最低伤害。
// 运行： node _analysis/wildarea.js
// 注意：不能用 'use strict'，因为引擎 getDamageInfo 里有隐式全局变量 ret
const fs = require('fs');
const path = require('path');

function loadObj(rel) {
    let src = fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
    src = src.replace(/^\s*var\s+[\w$]+\s*=\s*/, ''); // 去掉  var xxx =
    return eval('(' + src + ')');
}

const data = loadObj('project/data.js');
const items = loadObj('project/items.js');
const enemys = loadObj('project/enemys.js');
const funcs = loadObj('project/functions.js');

// ---- 最小 core 垫片 ----
const FLAGS = {};
const core = {
    status: {
        floorId: 'WildArea',
        checkBlock: { needCache: false, cache: {} },
        hero: {
            lv: 11, mana: 13, atk: 20, def: 10, mdef: 0,
            hpmax: 32, hp: 32, type1: 'Water', type2: null
        }
    },
    flags: data.flags,
    values: data.values,
    material: { items: items, enemys: enemys },
    _held: null,
    getRealStatusOrDefault(hero, name) {
        if (hero && hero[name] != null) return hero[name];
        return core.status.hero[name];
    },
    getStatusOrDefault(hero, name) { return core.getRealStatusOrDefault(hero, name); },
    getFlag(n, d) { return FLAGS[n] == null ? d : FLAGS[n]; },
    setFlag(n, v) { FLAGS[n] = v; },
    hasEquip(id) { return core._held === id; },
    hasSpecial(sp, n) {
        if (sp == null) return false;
        if (typeof sp === 'number') return sp === n;
        if (Array.isArray(sp)) return sp.indexOf(n) >= 0;
        return false;
    },
    extractBlocks() {},
    enemys: {}
};
core.enemys.hasSpecial = core.hasSpecial;
core.enemys.getEnemyInfo = funcs.enemys.getEnemyInfo;
core.enemys.getDamageInfo = funcs.enemys.getDamageInfo;
global.core = core;
global.main = { levelChoose: [] };
global.flags = FLAGS;

// ---- WildArea 30 只怪（tile -> id），按格子位置 (x,y) ----
const grid = {
    '2,0': 'redWizard', '10,0': 'princessEnemy',
    '0,2': 'rock', '2,2': 'redPriest', '4,2': 'brownWizard', '6,2': 'goldHornSlime',
    '8,2': 'whiteHornSlime', '10,2': 'octopus', '12,2': 'poisonZombie',
    '2,4': 'evilHero', '6,4': 'devilWarrior', '10,4': 'blueKing',
    '0,6': 'skeletonKnight', '2,6': 'redKing', '4,6': 'demonPriest', '6,6': 'swordsman',
    '8,6': 'magicMaster', '10,6': 'silverSlimelord', '12,6': 'fairyEnemy',
    '2,8': 'yellowKnight', '6,8': 'evilPrincess', '10,8': 'whiteSlimeman',
    '0,10': 'silverSlime', '2,10': 'blademaster', '4,10': 'evilFairy', '6,10': 'redSwordsman',
    '8,10': 'yellowPriest', '10,10': 'grayRock', '12,10': 'goldSlimelord',
    '2,12': 'dragon'
};

const MOVES = [' Tackle', ' Growl', ' WaterGun', ' RockSmash'];

// 在指定携带物下，遍历所有配招求最低伤害
function minDamage(enemyId, held) {
    const enemy = enemys[enemyId];
    core._held = held;
    let best = null, combo = null, turn = null;
    for (const a of MOVES) {
        for (const b of MOVES) {
            FLAGS.skill1 = a; FLAGS.skill2 = b;
            let info = null;
            try { info = core.enemys.getDamageInfo(enemy, null, null, null, 'WildArea'); } catch (e) { info = null; }
            if (info && info.damage != null) {
                if (best == null || info.damage < best) { best = info.damage; combo = [a, b]; turn = info.turn; }
            }
        }
    }
    return best == null ? null : { damage: best, combo, turn };
}

const nm = id => items[id] ? items[id].name : id;

console.log('=== WildArea 各怪最低伤害（hero Lv11 atk20 def10 mdef0 spd13）===\n');
console.log('格子(x,y)  怪物            Lv 属性          基础exp  戴蛋exp  最低伤害(水滴)  最低伤害(戴蛋)  回合  最优配招');
const rows = Object.keys(grid).sort((p, q) => {
    const [ax, ay] = p.split(',').map(Number), [bx, by] = q.split(',').map(Number);
    return ay - by || ax - bx;
});
for (const pos of rows) {
    const id = grid[pos];
    const e = enemys[id];
    const water = minDamage(id, 'MysticWater'); // 战斗最优（可减伤）
    const egg = minDamage(id, null);            // 戴幸运蛋时无战斗加成
    const typ = e.type1 + (e.type2 ? '/' + e.type2 : '');
    const f = (r) => r == null ? '无法战斗' : String(r.damage);
    const comboStr = water ? water.combo.map(nm).join('+') : '-';
    console.log(
        pos.padEnd(9) + ' ' +
        (e.name).padEnd(8) + '  ' +
        ('Lv' + (e.level || '?')).padEnd(4) +
        typ.padEnd(13) + ' ' +
        String(e.exp).padStart(6) + '  ' +
        String(Math.floor(e.exp * 1.5)).padStart(6) + '  ' +
        f(water).padStart(12) + '  ' +
        f(egg).padStart(12) + '  ' +
        String(water ? water.turn : '-').padStart(4) + '  ' +
        comboStr
    );
}

// ---- 1血开局第一战分析 ----
console.log('\n=== 1血开局：相邻两只（先用背包伤药垫血可达 1 / 21 / 32 HP）===');
for (const [pos, dir] of [['2,0', '向右'], ['0,2', '向下']]) {
    const id = grid[pos];
    const r = minDamage(id, 'MysticWater');
    const d = r ? r.damage : null;
    const surv = hp => d == null ? '打不过' : (d < hp ? '可活(剩' + (hp - d) + ')' : '死');
    console.log(`${dir} ${enemys[id].name}(${pos}) 最低伤害=${d == null ? '无法战斗' : d}  | 1血:${surv(1)}  21血:${surv(21)}  32血:${surv(32)}`);
}
