"""佛耶戈，海克斯大乱斗 26.23。Python 3.8+，无第三方依赖。

python3 viego-burst.py            输出成装路线、逐档搜索、固定核心的续装
python3 viego-burst.py --verdict  比较四种场景和从三件到五件的综合伤害
python3 viego-burst.py --help     调整电震、狂妄和海妖的进场状态
"""
import argparse
from dataclasses import dataclass
from functools import lru_cache
from itertools import combinations, product


@dataclass(frozen=True)
class Item:
    gold: int
    ad: float
    crit: int = 0  # percentage points
    lethality: int = 0


BASE_AD = 125  # level 18
ITEMS = {
    "收集": Item(3000, 50, 25, 10), "无尽": Item(3500, 75, 25),
    "大穿": Item(3300, 35, 25), "吸蓝刀": Item(3050, 50, 25),
    "盾弓": Item(3000, 55, 25), "饮血": Item(3400, 80),
    "破败": Item(3200, 40), "三相": Item(3333, 36),
    "焚天": Item(3100, 40), "死舞": Item(3300, 60),
    "血手": Item(3200, BASE_AD * 0.5), "无穷": Item(3100, 65),
    "电震": Item(3000, 55, lethality=10), "狂妄": Item(2950, 55, lethality=18),
    "公理": Item(2750, 55, lethality=18), "赛瑞尔达": Item(3000, 45),
    "海妖": Item(3000, 45),
}
BUDGET = {3: 10000, 4: 13500, 5: 17000}
EXCLUSIVE = ({"三相", "吸蓝刀"}, {"大穿", "赛瑞尔达"}, {"血手", "盾弓"})
PARTS = {"披风": Item(600, 0, 15), "长剑": Item(350, 10), "十字镐": Item(875, 25)}


@dataclass(frozen=True)
class Target:
    hp: int
    armor: int
    mr: int
    bonus_hp: int


BACK = Target(2500, 100, 50, 0)
FRONT = Target(5000, 200, 100, 2000)


@dataclass(frozen=True)
class State:
    charged: bool
    hubris_ad: int  # temporary attack damage already active before W
    kraken_stacks: int


@dataclass
class Build:
    names: frozenset
    gold: int
    bonus_ad: float
    crit: float
    extra_crit_damage: float
    lethality: int
    spellblade: float


def make_build(names, state, part=None):
    names = frozenset(names)
    items = [ITEMS[key] for key in names]
    if part:
        items.append(PARTS[part])
    chance = sum(item.crit for item in items)
    bonus_ad = sum(item.ad for item in items) + max(0, chance - 100) * 0.45
    if "狂妄" in names:
        bonus_ad += state.hubris_ad
    crit = min(100, chance) / 100
    lethality = sum(item.lethality for item in items)
    if "电震" in names and state.charged:
        lethality += 15
    spellblade = 0
    if "三相" in names:
        spellblade = 2 * BASE_AD
    elif "吸蓝刀" in names:
        spellblade = 1.25 * BASE_AD + 50 * crit
    return Build(names, sum(i.gold for i in items), bonus_ad, crit,
                 1.3 if "无尽" in names else 1.0, lethality, spellblade)


def simulate(build, target, start_hp, combo, rolls, state):
    """Damage in one crit outcome. Collector executes immediately; no overkill."""
    names = build.names
    crit_bonus = build.extra_crit_damage
    total_ad = BASE_AD + build.bonus_ad
    amp = 1.05
    if "大穿" in names:
        amp *= 1 + min(0.15, target.bonus_hp / 10000)
    armor = target.armor * (0.65 if names & {"大穿", "赛瑞尔达"} else 1)
    physical = amp * 100 / (100 + max(0, armor - build.lethality))
    magic = amp * 100 / (100 + target.mr)
    hp = start_hp
    execute_below = 0.05 * target.hp if "收集" in names else 0
    mark = False
    first_auto = True
    spellblade_ready = True
    seen_q = False
    attacks = state.kraken_stacks
    rolls = iter(rolls)

    def hit(damage):
        nonlocal hp
        hp = max(0, hp - damage)
        if hp < execute_below:
            hp = 0

    def on_hit(crit):
        nonlocal attacks
        hit(physical * max(30, 0.06 * hp) * (1 + 0.7 * crit_bonus * crit))
        if "破败" in names:
            hit(physical * max(15, 0.09 * hp))
        attacks += 1
        if "海妖" in names and attacks % 3 == 0:
            missing = 1 - hp / target.hp
            hit(physical * 200 * (1 + 0.75 * missing))  # level 18

    def swing(ratio, sky=False):
        nonlocal spellblade_ready
        crit = next(rolls)
        multiplier = 1 + crit_bonus * crit
        if sky:
            multiplier = 0.8 * (1 + crit_bonus)
        on_hit(crit or sky)
        if spellblade_ready:
            hit(physical * build.spellblade)
            spellblade_ready = False
        hit(physical * ratio * total_ad * multiplier)

    for key in combo:
        if hp == 0:
            break
        if key == "W":
            if "电震" in names and state.charged:
                hit(physical * 0.08 * hp)
            hit(magic * 300)
            mark = True
        elif key == "Q":
            if seen_q:  # second Q after both Q and Spellblade are ready
                spellblade_ready = True
            seen_q = True
            hit(physical * (85 + 0.7 * total_ad) * (1 + 0.6 * build.crit * crit_bonus))
            mark = True
        elif key == "A":
            swing(1.0, first_auto and "焚天" in names)
            first_auto = False
            if mark:
                swing(0.2)
                mark = False
        elif key == "R":
            missing_hp = target.hp - hp  # snapshot on R impact, before on-hit
            on_hit(False)  # conservative for the innate %-HP on-hit carried by R
            if spellblade_ready:
                hit(physical * build.spellblade)
                spellblade_ready = False
            base = 1.2 * total_ad * (1 + 0.7 * build.crit * crit_bonus)
            hit(physical * (base + missing_hp * (0.2 + 0.0005 * build.bonus_ad)))
            if mark:
                swing(0.2)
                mark = False
        else:
            raise ValueError(key)
    return start_hp - hp


ROLLS = {"WQAR": 2, "WQAQAR": 4, "WQARQA": 4, "WAQR": 3, "WAQAR": 4}


@lru_cache(maxsize=None)
def outcomes(chance, count):
    if chance in (0, 1):
        return [((int(chance),) * count, 1)]
    return [(rolls, chance ** sum(rolls) * (1 - chance) ** (count - sum(rolls)))
            for rolls in product((0, 1), repeat=count)]


def average(build, target, combo, state):
    return sum(weight * simulate(build, target, target.hp, combo, rolls, state)
               for rolls, weight in outcomes(build.crit, ROLLS[combo]))


def kill_floor(build, target, combo, state):
    # At 100% crit all normal attacks crit even in the worst possible outcome.
    rolls = (int(build.crit == 1),) * ROLLS[combo]
    low, high = 0, target.hp
    while low < high:
        mid = (low + high + 1) // 2
        if simulate(build, target, mid, combo, rolls, state) >= mid:
            low = mid
        else:
            high = mid - 1
    return low


def scores(build, state):
    return (kill_floor(build, BACK, "WQAR", state),
            average(build, FRONT, "WQAR", state),
            average(build, FRONT, "WQAQAR", state))


def search(state, evaluate=scores):
    results = {}
    for size, budget in BUDGET.items():
        rows = []
        for names in combinations(ITEMS, size):
            selected = frozenset(names)
            if any(group <= selected for group in EXCLUSIVE):
                continue
            build = make_build(selected, state)
            if build.gold <= budget:
                rows.append((build, evaluate(build, state)))
        results[size] = rows
    return results


def leaders(rows, required, metric):
    eligible = [(b, v[metric]) for b, v in rows if required <= b.names]
    top = max(score for _, score in eligible)
    return sorted((b for b, s in eligible if abs(s - top) < 1e-7),
                  key=lambda b: (b.gold, sorted(b.names)))


ROUTES = {
    "常规暴击": ["收集", "无尽", "大穿", "死舞", "盾弓"],
    "特效半肉战士": ["破败", "三相", "大穿", "血手", "死舞"],
    "焚天战士转穿透": ["破败", "焚天", "死舞", "大穿", "血手"],
    "狂妄转暴击": ["狂妄", "收集", "无尽", "大穿", "死舞"],
}


def report(state):
    for title, route in ROUTES.items():
        for size in BUDGET:
            build = make_build(route[:size], state)
            print(title, size, build.gold, *(round(x) for x in scores(build, state)))
    results = search(state)
    for size, rows in results.items():
        print(f"\n{size} 件，{len(rows)} 组；指标顺序为后排 WQAR 保守击杀线、前排 WQAR / WQAQAR 平均伤害")
        for core in [set(), {"电震", "破败", "大穿"}, {"收集", "无尽", "大穿"},
                     {"电震", "收集", "大穿"}]:
            for idx in range(3):
                tied = leaders(rows, core, idx)
                best = tied[0]
                print(sorted(core), idx + 1, " / ".join(sorted(best.names)),
                      best.gold, round(scores(best, state)[idx]), f"并列 {len(tied)}")


SCENARIOS = ((BACK, "WQAR"), (BACK, "WQAQAR"), (FRONT, "WQAR"), (FRONT, "WQAQAR"))


def full_health_damage(build, state):
    return tuple(average(build, target, combo, state) for target, combo in SCENARIOS)


def report_verdict(state):
    damage = {}
    relative = {}
    for size, rows in search(state, full_health_damage).items():
        maxima = tuple(max(column) for column in zip(*(values for _, values in rows)))
        damage[size] = {b.names: values for b, values in rows}
        for build, values in rows:
            relative[build.names] = tuple(value / peak for value, peak in zip(values, maxima))

    # Each route is an unordered three-item core, then two individual purchases.
    # Among paths tied for a single fight, prefer the better all-around path.
    labels = ["综合", "后排 WQAR", "后排 WQAQAR", "前排 WQAR", "前排 WQAQAR"]
    best = {}
    count = 0
    for five in damage[5]:
        for fifth in sorted(five):
            four = five - {fifth}
            if four not in damage[4]:
                continue
            for fourth in sorted(four):
                three = four - {fourth}
                if three not in damage[3]:
                    continue
                count += 1
                path = (three, four, five)
                scenario_scores = [sum(column) / 3 for column in zip(*(relative[k] for k in path))]
                overall = sum(scenario_scores) / len(scenario_scores)
                for label, score in zip(labels, [overall] + scenario_scores):
                    rank = (round(score, 12), round(overall, 12))
                    if label not in best or rank > best[label][0]:
                        best[label] = rank, path, fourth, fifth

    print(f"共 {count} 条不卖装备的路线，三至五件、四种场景分别等权。")
    for label in labels:
        (score, _), path, fourth, fifth = best[label]
        print(label, f"{100 * score:.2f}%", "＋".join(sorted(path[0])), "→", fourth, "→", fifth)
        for size, names in enumerate(path, start=3):
            print(size, *(round(x) for x in damage[size][names]))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--uncharged", action="store_true", help="全套均无电震盈能触发")
    parser.add_argument("--hubris-ad", type=int, default=0, help="进场时已激活的狂妄额外 AD")
    parser.add_argument("--kraken-stacks", type=int, choices=(0, 1, 2), default=0)
    output = parser.add_mutually_exclusive_group()
    output.add_argument("--verdict", action="store_true", help="按四种场景的满血平均伤害给出综合路线")
    output.add_argument("--build", nargs="+", choices=ITEMS, help="单独核算指定的三至五件成装")
    parser.add_argument("--part", choices=PARTS, help="为单套出装计入一件过渡散件，另留鞋位")
    args = parser.parse_args()
    state = State(not args.uncharged, args.hubris_ad, args.kraken_stacks)
    if args.hubris_ad < 0:
        parser.error("狂妄的额外攻击力不能为负")
    if args.part and (not args.build or len(args.build) >= 5):
        parser.error("散件需要指定三件或四件成装")
    if args.verdict:
        report_verdict(state)
    elif args.build:
        selected = set(args.build)
        if (not 3 <= len(selected) <= 5 or len(selected) != len(args.build)
                or any(group <= selected for group in EXCLUSIVE)):
            parser.error("请选择三至五件可同时持有的不同装备")
        build = make_build(selected, state, args.part)
        print("金币", build.gold, "暴击率", f"{build.crit:.0%}")
        print("连招   后排平均伤害   后排保守击杀线   前排平均伤害   前排保守击杀线")
        for combo in ROLLS:
            print(combo, round(average(build, BACK, combo, state)),
                  kill_floor(build, BACK, combo, state), round(average(build, FRONT, combo, state)),
                  kill_floor(build, FRONT, combo, state))
    else:
        report(state)
