// 诅咒收益测试（离线，复用引擎 getDamageInfo）
// node _analysis/curse_test.js
const fs = require('fs');
const path = require('path');
function loadObj(rel, prefix) {
    let src = fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
    src = src.replace(prefix || /^\s*var\s+[\w$]+\s*=\s*/, '');
    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');

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, enemys }, _held: null,
    getRealStatusOrDefault(h, n) { return (h && h[n] != null) ? h[n] : core.status.hero[n]; },
    getStatusOrDefault(h, n) { return core.getRealStatusOrDefault(h, n); },
    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) { return sp == null ? false : (typeof sp === 'number' ? sp === n : (Array.isArray(sp) ? sp.indexOf(n) >= 0 : 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;

// ---- 把英雄升到 ~Lv27 ----
const LUP = data.firstData.levelUp.map(e => {
    const d = { need: Number(e.need), datk:0, ddef:0, dhpmax:0, dhp:0, dmana:0, dmdef:0, evolve:false };
    (e.action||[]).forEach(a => {
        if (a && a.type === 'setValue' && a.operator === '+=') {
            const v = Number(a.value); if (isNaN(v)) return;
            if (a.name==='status:atk') d.datk+=v; else if (a.name==='status:def') d.ddef+=v;
            else if (a.name==='status:hpmax') d.dhpmax+=v; else if (a.name==='status:hp') d.dhp+=v;
            else if (a.name==='status:mana') d.dmana+=v; else if (a.name==='status:mdef') d.dmdef+=v;
        } else if (a && a.type === 'function' && /type2\s*=\s*["']Ground["']/.test(a.function||'')) d.evolve = true;
    });
    return d;
});
const H = { lvIdx: 7, exp: 85, atk: 20, def: 10, mdef: 0, hpmax: 32, mana: 13, type2: null };
const TARGET = 27; // 目标等级
while (H.lvIdx < LUP.length && (H.lvIdx - 1 + 5) < TARGET) { // 升到 Lv27（lvIdx-1+5=当前等级）
    const L = LUP[H.lvIdx];
    H.atk += L.datk; H.def += L.ddef; H.mdef += L.dmdef; H.hpmax += L.dhpmax; H.mana += L.dmana;
    if (L.evolve) H.type2 = 'Ground';
    H.lvIdx++;
}
console.log('英雄 Lv' + (H.lvIdx - 1 + 5) + '：atk' + H.atk + ' def' + H.def + ' mdef' + H.mdef
    + ' hpmax' + H.hpmax + ' speed(mana)' + H.mana + ' 属性Water' + (H.type2 ? '/' + H.type2 : ''));

function setHero() {
    const h = core.status.hero;
    h.lv = H.lvIdx - 1 + 5; h.atk = H.atk; h.def = H.def; h.mdef = H.mdef;
    h.hpmax = H.hpmax; h.hp = H.hpmax; h.mana = H.mana; h.type1 = 'Water'; h.type2 = H.type2;
}
const ATTACKS = [' WaterPulse', ' RockSlide', ' MudShot', ' RockSmash', ' WaterGun'];

// 注入几个"自定义敌人技能"用于测试技能设计（feature 字段都是引擎真实支持的）
items[' SkPlain'] = { name: '普通攻击', feature: { type: 'Flying', factor: 1.0 } };
items[' SkHeal']  = { name: '攻击+每回合自愈10%', feature: { type: 'Steel', factor: 1.0, maxHPrecover: 0.10 } };
items[' SkDrain'] = { name: '吸血(回40%伤害)',   feature: { type: 'Steel', factor: 1.0, recover: 0.4 } };
items[' SkBurn']  = { name: '攻击+灼烧(降你输出)', feature: { type: 'Fire',  factor: 0.8, enemyStatusCond: 'Burn', enemyCondFactor: 1 } };
items[' SkIron']  = { name: 'turn1铁壁(自身防+1)', feature: { type: 'Steel', isStatusMove: 1, selfDef: 1 } };
items[' SkAtkDn'] = { name: '攻击+降你攻击',       feature: { type: 'Steel', factor: 0.9, enemyAtk: -1 } };

// 给定敌人，返回 {noCurse, curse}：各自"最优攻击招"的最低受伤
function evalEnemy(e) {
    setHero(); core._held = null;
    const calc = (s1, s2) => { FLAGS.skill1 = s1; FLAGS.skill2 = s2;
        let info = null; try { info = core.enemys.getDamageInfo(e, null, null, null, 'WildArea'); } catch (_) {}
        return info ? info.damage : null; };
    let noCurse = null, ncMove = null, curse = null, cMove = null;
    for (const a of ATTACKS) {
        const d = calc(a, a); // 全程这一招
        if (d != null && (noCurse == null || d < noCurse)) { noCurse = d; ncMove = a; }
        const dc = calc(' Curse', a); // 第1回合诅咒，之后这一招
        if (dc != null && (curse == null || dc < curse)) { curse = dc; cMove = a; }
    }
    return { noCurse, ncMove, curse, cMove };
}

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

// ---- 设计的几只怪 ----
const TESTS = [
    { tag: '①肉盾(普通,无弱点,慢)',       e: { name:'测试肉盾', hp:180, atk:30, def:38, type1:'Normal', type2:null,    skill1:' Tackle',    speed:18, level:28, exp:500, money:12, special:0, point:0 } },
    { tag: '②草龙(抗水×0.25抗地)',        e: { name:'测试草龙', hp:190, atk:32, def:34, type1:'Grass',  type2:'Dragon', skill1:' AirSlash',  speed:18, level:28, exp:520, money:12, special:0, point:0 } },
    { tag: '③钢飞(免疫地震,只水可破)',     e: { name:'测试钢飞', hp:175, atk:34, def:34, type1:'Steel',  type2:'Flying', skill1:' AirSlash',  speed:18, level:28, exp:520, money:12, special:0, point:0 } },
    { tag: '④水系肉(抗水STAB)',           e: { name:'测试水肉', hp:165, atk:32, def:30, type1:'Water',  type2:null,     skill1:' WaterGun',  speed:18, level:28, exp:480, money:11, special:0, point:0 } },
    { tag: '⑤错误示范:脆皮飞行(4×弱岩)',   e: { name:'测试脆飞', hp:140, atk:38, def:26, type1:'Bug',    type2:'Flying', skill1:' AirSlash',  speed:20, level:28, exp:520, money:12, special:0, point:0 } },
    { tag: '⑥错误示范:低血高攻',          e: { name:'测试脆皮', hp:45,  atk:62, def:12, type1:'Fire',   type2:null,     skill1:' Ember',     speed:60, level:27, exp:250, money:7,  special:0, point:0 } },
];

console.log('\n招式说明：第1回合诅咒(攻防+1/速-1) → 第2回合起 你伤害×1.5、受伤×0.667');
console.log('─'.repeat(78));
console.log('怪(设计意图)'.padEnd(26) + '直接打(最低受伤)   诅咒流(最低受伤)   差值   结论');
console.log('─'.repeat(78));
for (const t of TESTS) {
    const r = evalEnemy(t.e);
    const f = v => v == null ? '打不过' : String(v);
    const diff = (r.noCurse != null && r.curse != null) ? (r.noCurse - r.curse) : null;
    const verdict = diff == null ? '-' : (diff > 0 ? '诅咒省 ' + diff + ' 血 ✓' : (diff < 0 ? '诅咒亏 ' + (-diff) + ' 血 ✗' : '持平'));
    console.log(
        t.tag.padEnd(24) + '  ' +
        (f(r.noCurse) + '(' + (r.ncMove ? nm(r.ncMove) : '-') + ')').padEnd(16) + ' ' +
        (f(r.curse) + '(' + (r.cMove ? nm(r.cMove) : '-') + ')').padEnd(16) + ' ' +
        (diff == null ? '-' : (diff > 0 ? '+' : '') + diff).padStart(5) + '   ' + verdict);
}
console.log('─'.repeat(78));
console.log('(怪的属性/数值是我随手设计的，仅用于看诅咒收益规律；可按需调整再跑)');

// ===== 技能设计对比：同一只钢/飞肉怪(hp175 atk34 def34 速18)，换不同技能 =====
const BASE = { name:'钢飞', hp:175, atk:34, def:34, type1:'Steel', type2:'Flying', speed:18, level:28, exp:520, money:12, special:0, point:0 };
const SKILLTESTS = [
    { tag: '普通攻击(基准)',          s1:' SkPlain'  },
    { tag: '①自愈攻击(每回合回10%血)', s1:' SkHeal'   },
    { tag: '②吸血(回40%所受伤害)',     s1:' SkDrain'  },
    { tag: '③灼烧攻击(烧你→你输出↓)',  s1:' SkBurn'   },
    { tag: '④turn1铁壁+turn2普攻',     s1:' SkIron', s2:' SkPlain' },
    { tag: '⑤攻击+降你攻击',          s1:' SkAtkDn'  },
];
console.log('\n\n===== 技能设计对比（同一只钢/飞肉怪，只换技能）=====');
console.log('看两点：诅咒省多少血(收益越大说明该技能越"逼"你用诅咒)，以及绝对难度');
console.log('─'.repeat(78));
console.log('技能设计'.padEnd(26) + '直接打   诅咒流   诅咒省   备注');
console.log('─'.repeat(78));
for (const t of SKILLTESTS) {
    const e = Object.assign({}, BASE, { skill1: t.s1, skill2: t.s2 });
    const r = evalEnemy(e);
    const f = v => v == null ? '打不过' : String(v);
    const diff = (r.noCurse != null && r.curse != null) ? (r.noCurse - r.curse) : null;
    console.log(
        t.tag.padEnd(24) + '  ' + f(r.noCurse).padStart(5) + '  ' + f(r.curse).padStart(6) + '  ' +
        (diff == null ? '   -' : (diff > 0 ? '+' : '') + diff).padStart(6) + '   ' +
        (r.noCurse == null ? '直接打不过(太肉)' : (diff > 15 ? '诅咒收益大✓' : (diff > 0 ? '诅咒小赚' : '诅咒无用'))));
}
console.log('─'.repeat(78));
