#!/usr/bin/env python
"""advisor — 面向大模型的 FRA Premier Draft 抓牌 / 配牌引擎。

设计（见 README §8）：
  * **确定性**：同一 state 必得同一结果；不联网、无副作用。
  * **stdout 只输出 JSON**；人话放在 `advice` 字段（`--format text` 可直出文字）。
  * 状态从 `--state <file>` 或 `--state -`（stdin）读入。

子命令：
  pick    当前包该抓哪张、该往哪个色组/思路走
  build   按牌池配出一套 40 张（23 咒语 + 17 地）
  archetypes  列出所有子流派的拟合度
  check   自检 value/ 数据是否齐全

state.json 示例：
{
  "pack":  [{"name": "Last Gasp"}, {"name": "Icy Reception", "count": 1}],
  "pool":  [{"name": "Extended Absence", "count": 2}, ...],
  "colors": "BG"                    // 可选：已承诺主色
}

退出码：0 正常 · 2 输入有误 · 3 依赖数据缺失
"""
from __future__ import annotations

import argparse
import difflib
import json
import math
import re
import sys
from collections import Counter
from pathlib import Path

def _find_root() -> Path:
    p = Path(__file__).resolve().parent
    for cand in [p, *p.parents]:
        if (cand / "scripts").is_dir() and (cand / "README.md").exists():
            return cand
    return p.parents[1]


ROOT = _find_root()
DEFAULT_SNAP = "FRA20261011"
ALL_COLORS = "WUBRG"
P0 = 0.5626                     # 全场平均 GIH（见 README §5.0.1）

# —— 打分权重（第一版猜测值，可调）——
W_GIH = 0.85        # 全场 GIH 相对 P0（百分点）；修好 card_value 的口径后重新对拍校准
                    # （原 0.55 是在“模板外牌基础分没乘 W_GIH”的旧口径下调出来的）
W_IWD = 0.50        # 基准质量里 IWD（drawn_improvement = 抽到提升）的占比：
                    #   base = (1-W_IWD)*(GIH-P0) + W_IWD*IWD
                    # 消融（FRA20261011, 44 局）：纯 GIH top1 45.3%/top3 75.0%/曲线 3.57；
                    #   50/50 -> 47.6%/77.0%/3.37（牌组强度不变）；纯 IWD 47.7%/79.1%/3.88。
                    # 纯 GIH 会低估“抽到才强”的牌，也是界面里 IIH 与 gih 分项偏差大的原因。
W_AFF = 0.80        # 色对绝对质量 affinity
W_AFF_CLUSTER = 0.0    # 本簇表现提升 affinity_cluster
                       # 消融（scripts/tune_weights.py, FRA20261011, 77 局）：
                       #   0.45 -> top1 45.2% / top3 76.9% / 曲线L1 5.45 / 生物 70/77
                       #   0.15 -> 45.6% / 77.5% / 4.88 / 73
                       #   0.00 -> 46.0% / 78.0% / 4.14 / 76   ← 全项最好
                       # 簇是软划分（§5.0.2），簇内 lift 噪声大，重量上去反而伤害卡值。
W_SYNERGY = 1.60    # 与牌池的协同（Σ lift−1）
W_CURVE = 3.50      # 曲线缺口（正=还差 / 负=已超）—— 对拍验证下来 3.5 最优
CURVE_OVER_MULT = 2.0   # 「超量」额外倍数：curve_need<0 的部分再乘这个（曲线冗余加强）
CURVE_OVER_CAP = -3.0   # 超量惩罚的下限（随 CURVE_OVER_MULT 一起加深，避免一个桶把总分吞掉）
W_SAT = 2.00        # 超出该思路实测上限（templates 的 max_copies）的重复惩罚（1.0→2.0 加强）
SAT_CAP = 1.5       # 超量惩罚的**上限**（张数）：限住“第 4 张同名牌直接 −6”这种失控项
W_ROLE = 3.00       # 角色缺口：按**目标张数的缺失比例**加权（缺得越狠给得越多，见 §5.0.2 第 38 条）
W_ANTI = 0.60       # 反协同（模板 antisynergy，lift<1）
W_PKG = 0.40        # 跨思路牌对协同（packages.json 的 top_pairs）
W_OPEN = 1.20       # 颜色开放度信号（这包在传什么色）—— 早期权重高，后期淡出
LOCK_FROM_PICK = 0   # 0 = 不锁；>0 = 从该抓（1-based，总体）起硬锁思路：17 = P2P3
                     # 实测：锁 P2P3 蓝倾向不变、对拍前三 −2.8pt，所以默认关。
AFF_DEMEAN = True   # affinity 按色对去均值：只留“组内相对好坏”，去掉“哪个色对天生强”
W_MIN = 1.50        # 标配牌（min_copies=1 且还没拿到）的加成
W_COLOR = 1.50      # 颜色契合（已承诺色组）的**基准力度**
COLOR_IN_BONUS = 1.0  # 主色内加分倍数（1=+W_COLOR；0=只留离色惩罚）
CRE_DIV = 3.0       # cre 缺口的归一化分母（越小越狠；实测 3.0 曲线最贴，2.0 更狠但曲线 4.22→4.38）
COLOR_SOFT = 0.25     # 颜色项软化：0=二值（对拍最好 50.1%）；1=跨思路加权（46.0%）。0.25 只掉 0.5pt，但 RG 开放时绿牌不会被重罚
COLOR_RAMP = 12     # 牌池到这个张数时定色力度拉到 1（commit_arch 本身也要 pool≥12）
COLOR_LATE = 0.50   # 后段加码：牌池 >23 张后每多 19 张，力度再乘 (1+COLOR_LATE)
                    # 同口径对拍：0.5 → 整体 50.0%/后期 54.1%；全局加大 W_COLOR 反而更差
W_CRE = 2.00        # 生物比例缺口（偏离 archetype 目标时向回拉）
CRE_TOL = 0.10      # 生物比例允许偏离 archetype 目标的相对幅度（±10%）
CRE_SWAP_MAX = 8.0  # 为凑生物比例最多肯牺牲多少卡值（百分点）
TEMP = 6.0          # 拟合度 softmax 温度（越大越平均）

CURVE = [("1", lambda m: m <= 1), ("2", lambda m: m == 2), ("3", lambda m: m == 3),
         ("4", lambda m: m == 4), ("5", lambda m: m == 5), ("6+", lambda m: m >= 6)]
# 完美基线曲线（合计 23 张咒语）。实际目标 = 基线打底 + 该 stream 实测均值浮动，
# 单靠簇内均值会被小样本带偏（比如某些簇 4 费只有 2.3 张），单靠基线又丢了思路差异。
BASELINE_CURVE = {"1": 2, "2": 7, "3": 6, "4": 4, "5": 3, "6+": 1}
CURVE_BLEND = 0.5   # 0 = 完全按基线，1 = 完全按该 stream 实测均值
BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
COLOR_BASIC = {"W": "Plains", "U": "Island", "B": "Swamp", "R": "Mountain", "G": "Forest"}
BASIC_COLOR = {v: k for k, v in COLOR_BASIC.items()}


# ---------------------------------------------------------------- 基础工具
def die(code: int, msg: str) -> None:
    print(json.dumps({"error": msg}, ensure_ascii=False), file=sys.stdout)
    sys.exit(code)


def color_requirements(mana_cost: str):
    """→ (硬要求色集合, 可选色组列表)。

    普通符号 `{2}{U}{U}` → `({U}, [])`
    双色混血 `{U/B}`     → `(set(), [{U,B}])`   「U 或 B 任一即可」
    单色混血 `{2/W}`     → `(set(), [])`         「2 点通用法术力也能付」
    非瑞 `{W/P}`         → `(set(), [])`         「2 点生命也能付」

    只跳过“能拿通用法术力/生命付掉”的符号；真正强制面色的混血必须记下来，
    否则 `{U/B}` 的牌会变成“不需要任何颜色”，对所有思路 color_fit 都返回 1.0。
    """
    hard, ors = set(), []
    for sym in re.findall(r"\{([^}]+)\}", mana_cost or ""):
        parts = sym.split("/")
        cols = [ch for p in parts for ch in p if ch in ALL_COLORS]
        if not cols:
            continue
        if len(parts) > 1:
            if all(p in ALL_COLORS for p in parts) and len(cols) > 1:
                ors.append(frozenset(cols))        # {U/B}：任一即可
            # {2/W} / {W/P} 可以用通用法术力或生命付 → 不算颜色要求
            continue
        hard |= set(cols)
    return frozenset(hard), tuple(ors)


def colors_ok(hard, ors, allowed) -> bool:
    """硬要求全在 allowed 里，且每个混血组至少命中一种颜色。"""
    allowed = set(allowed)
    return set(hard) <= allowed and all(set(g) & allowed for g in ors)


def required_colors(mana_cost: str) -> set:
    """该牌**硬要求**的颜色（不含能拿通用法术力替代的混血符号）。"""
    return set(color_requirements(mana_cost)[0])


def curve_bucket(cmc) -> str:
    m = cmc or 0
    for name, fn in CURVE:
        if fn(m):
            return name
    return "6+"


def target_curve(d: Data, t: dict) -> dict:
    """该 stream 的曲线目标：完美基线打底 + 簇内实测均值浮动，归一到 23 张。

    实测值取自模板 `deck_params.curve_targets`（核心牌表的平均张数）。
    结果缓存在模板 dict 上，供 curve_need / build 重复使用。
    """
    cached = t.get("_curve_targets")
    if cached is not None:
        return cached
    obs = (t.get("deck_params") or {}).get("curve_targets") or {}
    n = sum(v for v in obs.values() if v) or 0.0
    if n <= 0:                                     # 簇数据缺失 → 纯基线
        out = dict(BASELINE_CURVE)
    else:
        out = {b: (1.0 - CURVE_BLEND) * base + CURVE_BLEND * (obs.get(b, 0.0) * 23.0 / n)
               for b, base in BASELINE_CURVE.items()}
    s = sum(out.values()) or 1.0
    out = {b: v * 23.0 / s for b, v in out.items()}
    t["_curve_targets"] = out
    return out


class Data:
    def __init__(self, snap: str):
        self.snap = snap
        self.vdir = ROOT / "value" / snap
        sdir = ROOT / "data/17lands" / snap / "stats"
        if not (self.vdir / "templates/_index.json").exists():
            die(3, f"缺少 {self.vdir}/templates/_index.json —— 请先跑 build_templates_contract.py")
        self.index = json.loads((self.vdir / "templates/_index.json").read_text(encoding="utf-8"))
        _sm = re.match(r"([A-Za-z]+)", snap or "")
        _pfx = ((_sm.group(1) if _sm else "FRA").upper()) + ".PremierDraft"
        self.templates = {}
        for slug in self.index:
            p = self.vdir / "templates" / f"{_pfx}.{slug}.json"
            if not p.exists():
                _g = sorted((self.vdir / "templates").glob(f"*.PremierDraft.{slug}.json"))
                p = _g[0] if _g else p
            if p.exists():
                t = json.loads(p.read_text(encoding="utf-8"))
                t["_cardmap"] = {c["name"]: c for c in t["cards"]}
                self.templates[slug] = t
        # （其他）= 「本对两个子流派都装不下的离群牌表」的残差桶，它不是一个能走的思路。
        # 任何打分 / 推荐 / 拟合度都必须把它排除在外，否则它会占据权重、甚至变成推荐。
        self.main = [s for s in self.templates if not s.endswith("-Other")]
        self.cdata = {}
        cd = sdir / "card_data.json"
        if cd.exists():
            for c in json.loads(cd.read_text(encoding="utf-8"))["data"]:
                self.cdata[c["name"]] = c
        # 卡牌类型兜底：card_data.json 覆盖不全时用 value 侧 cards.json（含本快照全部卡）
        self._ctypes = {}
        cj = self.vdir / "cards.json"
        if cj.exists():
            try:
                _cj = json.loads(cj.read_text(encoding="utf-8"))
                for c in _cj.get("cards", []):
                    self._ctypes[c.get("name")] = c.get("types") or ""
                # P0 = 本快照的 field mean GIH（不能沿用别的系列！）
                # FRA 0.5626 / TRK 0.5538：写错会让所有 gih 分量系统性偏移。
                _fm = _cj.get("field_mean_gih_wr")
                if _fm is not None:
                    global P0
                    P0 = float(_fm)
            except Exception:
                pass
        # reference decks (medoid) —— build 时可当锚点
        self.refs = {}
        rd = self.vdir / "reference_decks"
        if rd.exists():
            for p in rd.glob("*.json"):
                self.refs[p.stem] = json.loads(p.read_text(encoding="utf-8"))
        # 跨思路牌对协同（packages.json 的 top_pairs）—— 双向查表
        self.pkg_pairs = {}
        pj = self.vdir / "packages.json"
        if pj.exists():
            try:
                for e in (json.loads(pj.read_text(encoding="utf-8")).get("top_pairs") or []):
                    a, b, lift = e.get("a"), e.get("b"), float(e.get("lift") or 1.0)
                    if a and b and lift > 1.0:
                        for k in ((a, b), (b, a)):
                            self.pkg_pairs[k] = self.pkg_pairs.get(k, 0.0) + (lift - 1.0)
            except Exception:
                pass
        # 小缓存：mana_cost/cmc/色符 否则每次都要扫 26 个模板
        self._mc, self._cmc, self._req = {}, {}, {}
        # win_rate → ever_drawn_win_rate 的一元线性回归（17lands 对 16 张牌没给后者）
        xs = [(c["win_rate"], c["ever_drawn_win_rate"]) for c in self.cdata.values()
              if c.get("win_rate") is not None and c.get("ever_drawn_win_rate") is not None]
        self._cal = None
        if len(xs) >= 20:
            n = len(xs)
            mx = sum(a for a, _ in xs) / n
            my = sum(b for _, b in xs) / n
            vx = sum((a - mx) ** 2 for a, _ in xs) / n
            cov = sum((a - mx) * (b - my) for a, b in xs) / n
            if vx > 0:
                self._cal = (mx, my, cov / vx)
        # play_rate → ever_drawn_win_rate 的经验斜率（给完全没胜率的牌用）。
        # 17lands 对样本太小的牌直接把胜率置空，但 play_rate 一定有：
        # 这些牌 play_rate 只有 0.5%~8%（均值 64%），说明根本没人用 → 是真的差牌。
        pr = [(c["play_rate"], c["ever_drawn_win_rate"]) for c in self.cdata.values()
              if c.get("play_rate") is not None and c.get("ever_drawn_win_rate") is not None]
        self._pr = None
        if len(pr) >= 20:
            n = len(pr)
            mx = sum(a for a, _ in pr) / n
            vx = sum((a - mx) ** 2 for a, _ in pr) / n
            cov = sum((a - mx) * (b - P0) for a, b in pr) / n
            if vx > 0:
                self._pr = (mx, cov / vx)

    def known_names(self):
        """本快照认识的所有牌名（卡数据 + 所有模板 + 基本地）。"""
        s = self.__dict__.get("_known")
        if s is None:
            s = set(BASICS) | set(self.cdata)
            for t in self.templates.values():
                s |= set(t["_cardmap"])
            self._known = s
        return s

    def unknown(self, names):
        kn = self.known_names()
        return [n for n in names if n not in kn]

    def gjwr(self, name: str):
        """这张牌到底强不强（统一到 ever_drawn_win_rate 口径）。

        17lands 对 16/290 张牌只给了 win_rate。用同时有两项的 274 张做回归
        把 win_rate 外推过去，比直接当“全场平均”靠谱得多——否则 Yargle
        （win_rate 44.8%）这种明显的弱牌会被当成中性牌。
        """
        c = self.cdata.get(name) or {}
        g = c.get("ever_drawn_win_rate")
        if g is None and self._cal is not None and c.get("win_rate") is not None:
            mx, my, k = self._cal
            g = P0 + k * (c["win_rate"] - mx)       # 以 P0 为中心，与未缺牌同一把尺
        if g is None and self._pr is not None and c.get("play_rate") is not None:
            mx, k = self._pr
            g = P0 + k * (c["play_rate"] - mx)
            # 外推夹紧：我们知道它们是差牌，但不知道差到哪里去
            g = max(P0 - 0.15, min(P0 + 0.05, g))
        return g

    # --- 卡的静态信息 ---
    def name_of(self, item) -> str:
        return item["name"] if isinstance(item, dict) else str(item)

    def mana_cost(self, name: str) -> str:
        if name in self._mc:
            return self._mc[name]
        v = None
        for t in self.templates.values():
            c = t["_cardmap"].get(name)
            if c:
                v = c.get("mana_cost") or ""
                break
        if v is None:
            c = self.cdata.get(name) or {}
            v = c.get("mana_cost") or c.get("manaCost") or ""
        self._mc[name] = v
        return v

    def cmc(self, name: str):
        if name in self._cmc:
            return self._cmc[name]
        v = None
        for t in self.templates.values():
            c = t["_cardmap"].get(name)
            if c and c.get("cmc") is not None:
                v = c["cmc"]
                break
        if v is None:
            v = (self.cdata.get(name) or {}).get("cmc")
        self._cmc[name] = v
        return v

    def req(self, name: str):
        """该牌的 (硬要求色, 可选混血组)，带缓存。"""
        v = self._req.get(name)
        if v is None:
            v = color_requirements(self.mana_cost(name))
            self._req[name] = v
        return v

    def req_colors(self, name: str) -> frozenset:
        """这张牌涉及的所有颜色（硬要求 ∪ 混血组），用于展示与统计。"""
        hard, ors = self.req(name)
        return frozenset(set(hard) | {c for g in ors for c in g})

    def rarity(self, name: str) -> str:
        c = self.cdata.get(name) or {}
        if c.get("rarity"):
            return c["rarity"].lower()
        for t in self.templates.values():
            cc = t["_cardmap"].get(name)
            if cc:
                return (cc.get("rarity") or "").lower()
        return "common"


# ---------------------------------------------------------------- 打分
def base_gih(d: Data, name: str, c) -> float:
    """基准质量：GIH（全场胜率）与 IWD（抽到提升）各半。

    纯 GIH 会低估“抽到才强 / 不抽就崩”的牌（它的 IIH 很高但 GIH 一般）；
    IWD 恰好捕这一面。消融显示 50/50 与人类选牌更一致、曲线也更贴。
    缺 GIH 时回归外推，再退化到簇内 gih_wr；缺 IWD 则回退纯 GIH。
    """
    g = d.gjwr(name)
    if g is None and c is not None:
        g = c.get("gih_wr")
    g = (g if g is not None else P0) - P0
    iwd = (d.cdata.get(name) or {}).get("drawn_improvement_win_rate")
    if iwd is None:
        return g
    return (1.0 - W_IWD) * g + W_IWD * float(iwd)


def affinity_value(d: Data, name: str, t: dict) -> float:
    """模板里的 affinity 同时带“组内相对好坏”与“色对绝对强弱”。

    后者是“蓝倾向”的推手（UB 全队 +2.6、WR 全队 −2.1）。`AFF_DEMEAN` 时按
    该色对去均值，只保留组内相对好坏（“哪个色对天生强”交给全局 GIH 去体现）。
    """
    c = t["_cardmap"].get(name)
    a = (c or {}).get("affinity")
    if a is None:
        return 0.0
    if not AFF_DEMEAN:
        return a
    mu = t.get("_aff_mu")
    if mu is None:
        vals = [cc.get("affinity") for cc in t["cards"] if cc.get("affinity") is not None]
        mu = (sum(vals) / len(vals)) if vals else 0.0
        t["_aff_mu"] = mu
    return a - mu


ROLE_W = {"removal": 1.0, "interaction": 0.7, "bomb": 0.5, "evasion": 0.6,
          "creature": 0.4, "payoff": 0.2, "filler": 0.0, "land": 0.0}


def role_targets(d: Data, t: dict) -> dict:
    """该思路的角色配比（用模板 expected_copies×roles 估，归一到比例；不靠单副 medoid）。"""
    cached = t.get("_role_tgt")
    if cached is not None:
        return cached
    raw = {}
    for c in t["cards"]:
        rs = [r for r in (c.get("roles") or []) if r in ROLE_W and r != "land"]
        if not rs:
            continue
        ec = float(c.get("expected_copies") or c.get("target_copies") or 0.0)
        for r in rs:
            raw[r] = raw.get(r, 0.0) + ec
    s = sum(raw.values()) or 1.0
    t["_role_tgt"] = {r: v / s for r, v in raw.items()}
    return t["_role_tgt"]


def role_deficit(d: Data, name: str, t: dict, have: dict) -> float:
    """按 archetype 的角色**目标张数**算“还缺多少”（0..1）。

    旧版是“占比缺口”：目标 8% - 当前 0% = 0.08，×ROLE_W×W_ROLE 只有 ~0.1，几乎看不见。
    现在：target_n = 占比×23，missing = 1 - 当前张数/target_n（完全没=1，已够=0），
    取“这张牌能填的最缺角色”的 ROLE_W×missing（不 sum，避免一牌多角色叠加）。
    """
    rs = [r for r in (t["_cardmap"].get(name) or {}).get("roles") or [] if ROLE_W.get(r)]
    if not rs:
        return 0.0
    tgt = role_targets(d, t)
    cur: dict = {}
    for nm, n in have.items():
        if nm in BASICS or is_land(d, nm) or color_fit(d, nm, t) <= 0:
            continue
        for r in (t["_cardmap"].get(nm) or {}).get("roles") or []:
            if r in ROLE_W:
                cur[r] = cur.get(r, 0.0) + n
    best = 0.0
    for r in rs:
        tgt_n = float(tgt.get(r, 0.0)) * 23.0
        if tgt_n <= 0.05:
            continue
        miss = max(0.0, 1.0 - cur.get(r, 0.0) / tgt_n)
        best = max(best, ROLE_W[r] * miss)
    return best


def antisynergy_with_pool(d: Data, name: str, t: dict, have: dict) -> float:
    """模板 antisynergy（lift<1）：带的“克制牌”已在池里就扣分。"""
    c = t["_cardmap"].get(name)
    if not c:
        return 0.0
    s = 0.0
    for e in c.get("antisynergy") or []:
        other = e.get("name") or e.get("mtga_id")
        if isinstance(other, int):
            other = next((k for k, v in t["_cardmap"].items() if v.get("mtga_id") == other), None)
        if other and other in have:
            s += max(0.0, 1.0 - float(e.get("lift") or 1.0))
    return s


def package_with_pool(d: Data, name: str, have: dict) -> float:
    """跨思路牌对协同（packages.json）：与池里任意牌的 co-occur lift−1 之和。"""
    return sum(d.pkg_pairs.get((name, other), 0.0) for other in have)


def color_openness(d: Data, pack, pick_index: int) -> dict:
    """颜色开放度：这包里“活得比 ALSA 预期更久”的好牌越多，该色越开。"""
    raw = {}
    for item in pack or []:
        nm = d.name_of(item)
        alsa = (d.cdata.get(nm) or {}).get("avg_seen")
        if alsa is None:
            continue
        late = float(pick_index) - float(alsa)
        if late <= 0:
            continue
        q = max(0.0, (d.gjwr(nm) or P0) - P0) * 100.0
        for ch in d.req_colors(nm):
            raw[ch] = raw.get(ch, 0.0) + late * (1.0 + q)
    if not raw:
        return {}
    mx = max(raw.values()) or 1.0
    return {k: v / mx for k, v in raw.items()}


def card_openness(d: Data, name: str, openness: dict) -> float:
    """这张牌在其颜色上的开放度（多色取最大）。

    无色牌（无面料要求）不属于任何颜色：取各色开放度的**均值**，
    既不因为“不沾色”而被算成 0（那样会被同包有色牌白赚一截），
    也不直接拿最大值（避免无色牌在开放包里过度占优）。
    """
    if not openness:
        return 0.0
    cols = d.req_colors(name)
    if not cols:
        return sum(openness.values()) / len(openness)
    return max((openness.get(ch, 0.0) for ch in cols), default=0.0)


def pool_extra(d: Data, name: str, t: dict, have: dict) -> float:
    """牌池相关的额外项：角色缺口 + 跨思路牌对 − 反协同（pick/build 共用）。"""
    return (W_ROLE * role_deficit(d, name, t, have)
            + W_PKG * package_with_pool(d, name, have)
            - W_ANTI * antisynergy_with_pool(d, name, t, have))


_UKEYS = ("gih", "affinity", "affinity_cluster", "synergy", "curve",
          "saturation", "role", "antisynergy", "package")


def u_components(d: Data, name: str, t: dict, have: dict, buckets: dict) -> dict:
    """该牌在该思路下的**命名分量**（可正可负），score 就是它们的加权和。"""
    c = t["_cardmap"].get(name)
    return {
        "gih": W_GIH * base_gih(d, name, c) * 100,
        "affinity": W_AFF * affinity_value(d, name, t),
        "affinity_cluster": W_AFF_CLUSTER * ((c or {}).get("affinity_cluster") or 0.0),
        "synergy": W_SYNERGY * synergy_with_pool(d, name, t, have),
        "curve": W_CURVE * curve_need(d, name, t, buckets),
        "saturation": -W_SAT * saturation(d, name, t, have),
        "role": W_ROLE * role_deficit(d, name, t, have),
        "antisynergy": -W_ANTI * antisynergy_with_pool(d, name, t, have),
        "package": W_PKG * package_with_pool(d, name, have),
    }


def card_value(d: Data, name: str, t: dict) -> float:
    """这张牌在该 archetype 里的“胜率优势”（百分点）。"""
    c = t["_cardmap"].get(name)
    if c is None:
        # 不在该思路模板里的牌：底子仍要与在模板里的同一口径（×W_GIH），
        # 否则“不属于这个思路”的牌反而拿到更高的基础分，与跨思路加权相悖。
        return W_GIH * base_gih(d, name, None) * 100
    return W_GIH * base_gih(d, name, c) * 100 \
        + W_AFF * affinity_value(d, name, t) \
        + W_AFF_CLUSTER * (c.get("affinity_cluster") or 0.0)


def color_fit(d: Data, name: str, t: dict) -> float:
    """1.0 = 只用主色；0.55 = 需要 splash；0 = 完全不合。

    混血 `{U/B}` 按「U 或 B 任一即可」判定，不是「不需要颜色」。
    """
    hard, ors = d.req(name)
    main = set((t.get("archetype") or "").upper())
    full = set((t.get("colors") or t["archetype"]).upper())
    if colors_ok(hard, ors, main):
        return 1.0
    if colors_ok(hard, ors, full):
        return 0.55
    return 0.0


def color_ok(d: Data, name: str, pair: str) -> bool:
    return bool(color_fit(d, name, {"archetype": pair, "colors": pair}))


def _type_str(d: Data, name: str) -> str:
    """卡牌类型字符串。优先 card_data.json，缺失时回退 value/cards.json。

    以前只看 `d.cdata`：只要某张牌在模板里有、但 17lands card_data 没收录，
    就会被当成咒语（污染曲线 / 生物比例 / 地数）。
    """
    tl = (d.cdata.get(name) or {}).get("types")
    if isinstance(tl, str) and tl:
        return tl
    if tl:
        return " ".join(str(x) for x in tl)
    return str(d._ctypes.get(name, ""))


def is_land(d: Data, name: str) -> bool:
    return "land" in _type_str(d, name).lower()


def is_creature(d: Data, name: str) -> bool:
    return "creature" in _type_str(d, name).lower()


def _land_fit(d: Data, name: str, t: dict) -> float:
    """非基本地在该思路里的分量：簇里包含率优先，其次全场使用率。"""
    c = t["_cardmap"].get(name)
    if c:
        return float(c.get("inclusion") or 0.0)
    cd = d.cdata.get(name) or {}
    return float(cd.get("play_rate") or 0.0) * 0.5


def _build_land_color_index() -> dict:
    """扫 data/mtgch 的 Forge 脚本，得到 `牌名 -> 可产色集合 | None(任意色)`。

    17lands 与 value 数据集里都没有“这张地产什么色”的字段（地牌的 color 列是空的），
    唯一结构化来源是 Forge 脚本的 `A:AB$ Mana ... Produced$` 行。
    """
    out = {}
    base = ROOT / "data" / "mtgch" / "cards"
    if not base.exists():
        return out
    for p in base.rglob("*.txt"):
        try:
            txt = p.read_text(encoding="utf-8", errors="ignore")
        except Exception:
            continue
        if "Produced$" not in txt:
            continue
        name = None
        toks = []
        for line in txt.splitlines():
            if name is None and line.startswith("Name:"):
                name = line[5:].strip()
            m = re.search(r"Produced\$\s*([^|]+)", line)
            if m:
                toks.extend(m.group(1).replace("Combo", " ").split())
        if not name:
            continue
        anyc = any(t in ("Chosen", "Any") for t in toks)
        cols = {ch for t in toks for ch in t if ch in ALL_COLORS}
        if anyc or len(cols) >= len(ALL_COLORS):
            out[name] = None                       # 任意色
        elif name not in out:
            out[name] = cols
        elif out[name] is not None:
            out[name] |= cols                      # 同名变体：并集
    return out


def _load_land_colors(d: "Data") -> dict:
    """惰性加载“地牌产色”索引，并缓存到 value/<snap>/land_colors.json。"""
    if getattr(d, "_land_colors", None) is not None:
        return d._land_colors
    cache = d.vdir / "land_colors.json"
    raw = None
    if cache.exists():
        try:
            j = json.loads(cache.read_text(encoding="utf-8"))
            raw = {k: (None if v == "*" else frozenset(v)) for k, v in j.items()}
        except Exception:
            raw = None
    if raw is None:
        raw = _build_land_color_index()
        try:
            cache.write_text(json.dumps(
                {k: ("*" if v is None else "".join(sorted(v, key=ALL_COLORS.index)))
                 for k, v in raw.items()},
                ensure_ascii=False, sort_keys=True), encoding="utf-8")
        except Exception:
            pass
    d._land_colors = raw
    return raw


def land_produced_colors(d: "Data", name: str):
    """该地可产的颜色：frozenset 颜色集 · None=任意色 · "unknown"=无数据。"""
    idx = _load_land_colors(d)
    if name not in idx:
        return "unknown"
    return idx[name]


def _land_helps(d: "Data", name: str, need) -> bool:
    """非基本地能不能产本套需要的色（任意色/数据缺失时放行）。"""
    if not need:
        return True
    pc = land_produced_colors(d, name)
    if pc == "unknown" or pc is None:
        return True
    return bool(pc & set(need))


def pool_counts(pool) -> dict:
    out = {}
    for item in pool or []:
        nm = item["name"] if isinstance(item, dict) else str(item)
        n = int(item.get("count", 1)) if isinstance(item, dict) else 1
        out[nm] = out.get(nm, 0) + n
    return out


def card_value_fit(d: Data, name: str, t: dict) -> float:
    """拟合度专用的“卡值”：**不含**色对绝对强度（affinity），
    只留 全场质量 + 本簇提升，这样跨 archetype 才可比。"""
    c = t["_cardmap"].get(name)
    if c is None:
        return W_GIH * base_gih(d, name, None) * 100
    return W_GIH * base_gih(d, name, c) * 100 \
        + W_AFF_CLUSTER * (c.get("affinity_cluster") or 0.0)


def archetype_fit(d: Data, slug: str, have: dict, topn: int = 23) -> float:
    """估算“按这个思路配出来的牌组有多强”= 最合适的 topn 张的卡值之和。

    地（含基本地）不计入：地牌的费用里没有色符，`color_fit` 对所有思路都返回 1.0，
    一张红黑双色地会把每一个含红/黑的思路都往上抬，等于用“色彩修正”冒充“契合度”。
    “该配几个地”是 build 阶段的事，不该参与拟合度。
    """
    t = d.templates[slug]
    vals = []
    for nm, n in have.items():
        if nm in BASICS or is_land(d, nm):
            continue
        cf = color_fit(d, nm, t)
        if cf > 0:
            vals.extend([cf * card_value_fit(d, nm, t)] * n)
    # 只算“值得进牌组”的牌：卡值为负 = 比全场平均还差，你不会用它，贡献应该是 0。
    # （否则往池子里加一张同色废牌反而会拉低 fit，方向是反的）
    vals = [v for v in vals if v > 0]
    vals.sort(reverse=True)
    return sum(vals[:topn])


def curve_have(d: Data, have: dict, t: dict) -> dict:
    buckets = {k: 0 for k, _ in CURVE}
    for nm, n in have.items():
        if nm in BASICS or is_land(d, nm) or color_fit(d, nm, t) <= 0:
            continue
        buckets[curve_bucket(d.cmc(nm))] += n
    return buckets


def synergy_with_pool(d: Data, name: str, t: dict, have: dict) -> float:
    c = t["_cardmap"].get(name)
    if not c:
        return 0.0
    s = 0.0
    for e in c.get("synergy") or []:
        other = e.get("name") or e.get("mtga_id")
        if isinstance(other, int):
            other = next((k for k, v in t["_cardmap"].items() if v.get("mtga_id") == other), None)
        if other and other in have:
            s += max(0.0, float(e.get("lift") or 1.0) - 1.0)
    return s


def is_legendary(d: Data, name: str) -> bool:
    cd = d.cdata.get(name) or {}
    return any("legendary" in str(t).lower() for t in (cd.get("types") or []))


def saturation(d: Data, name: str, t: dict, have: dict) -> float:
    """超出**该思路实测上限**的部分。

    模板里的 `max_copies` = 这个 stream 的单副最多带几张（实测，不是规则上限——
    轮抓是限制赛，没有 4 张限制）。Icy Reception 在 UB-Icy 是 3，Kiora 在多数思路是 1。
    拿超过这个数的副本，在该思路里就是真的没人这么打过。
    """
    c = t["_cardmap"].get(name)
    cap = int((c or {}).get("max_copies") or 0)
    if cap <= 0:                                   # 模板没收录 → 退回传奇规则
        return min(SAT_CAP, max(0.0, have.get(name, 0) + 1 - 2.0)) if is_legendary(d, name) else 0.0
    return min(SAT_CAP, max(0.0, have.get(name, 0) + 1 - cap))


def int_quota(targets: dict, n: int = 23) -> dict:
    """把小数目标曲线转成整数配额（最大余数法），合计恒为 n。"""
    base = {b: int(targets.get(b, 0) or 0) for b in BASELINE_CURVE}
    rem = n - sum(base.values())
    if rem > 0:
        order = sorted(BASELINE_CURVE, key=lambda b: -((targets.get(b, 0) or 0) - base[b]))
        for i in range(rem):
            base[order[i % len(order)]] += 1
    elif rem < 0:
        order = sorted(BASELINE_CURVE, key=lambda b: ((targets.get(b, 0) or 0) - base[b]))
        for i in range(-rem):
            b = order[i % len(order)]
            if base[b] > 0:
                base[b] -= 1
    return base


def curve_need(d: Data, name: str, t: dict, buckets: dict) -> float:
    """曲线缺口：**正 = 这个费用桶还差几张；负 = 已经超了**（超得越多扣得越狠）。

    以前只看缺口，超了直接返回 0，所以池子里已经 3 张 6 费时，第 4 张 6 费毫无代价
    —— 曲线会一路烂下去（“都 4 张六费牌了”）。现在超量同样计入，用同一个归一尺度。
    """
    if name in BASICS or is_land(d, name):
        return 0.0
    b = curve_bucket(d.cmc(name))
    target = float(target_curve(d, t).get(b, 0.0) or 0.0)
    if target <= 0:
        return 0.0
    gap = target - buckets.get(b, 0)
    if gap >= 0:                                   # 还差：正常拉动
        return gap / (target + 1.0)
    # 已超：在原有斜率上再乘 CURVE_OVER_MULT，曲线冗余的代价更大
    return max(CURVE_OVER_CAP, gap / (target + 1.0) * CURVE_OVER_MULT)


def archetype_weights(d: Data, fits: dict) -> dict:
    if not fits:
        return {}
    mx = max(fits.values())
    exps = {k: math.exp((v - mx) / TEMP) for k, v in fits.items()}
    tot = sum(exps.values()) or 1.0
    return {k: v / tot for k, v in exps.items()}


def _hyper_ge(sources: int, draws: int, pop: int, need: int) -> float:
    """P(X ≥ need)，X ~ 超几何(总体 pop, 成功 sources, 抽 draws)。"""
    if need <= 0:
        return 1.0
    hi = min(sources, draws)
    if need > hi or draws > pop:
        return 0.0
    denom = math.comb(pop, draws)
    if not denom:
        return 0.0
    return sum(math.comb(sources, k) * math.comb(pop - sources, draws - k)
               for k in range(need, hi + 1)) / denom


def sources_needed(pips: int, cmc, prob: float = 0.90, pop: int = 40) -> int:
    """在 `cmc` 回合前以 `prob` 概率看到 `pips` 个该色源，至少需要几个色源。"""
    draws = max(1, min(pop, 7 + max(int(round(cmc or 1)), 1) - 1))
    for s in range(0, pop + 1):
        if _hyper_ge(s, draws, pop, pips) >= prob:
            return s
    return pop


def mana_profile(d: Data, chosen) -> dict:
    """每种颜色：(总色符, 单卡最大色符, 该最大色符所在牌的费用)。"""
    prof = {}
    for nm, n in chosen.items():
        if nm in BASICS or is_land(d, nm):
            continue
        cmc = d.cmc(nm) or 0
        cnt = {}
        for sym in re.findall(r"\{([^}]+)\}", d.mana_cost(nm) or ""):
            if "/" in sym:
                continue
            for ch in sym:
                if ch in ALL_COLORS:
                    cnt[ch] = cnt.get(ch, 0) + 1
        for ch, k in cnt.items():
            tot, mx, mcmc = prof.get(ch, (0, 0, 0))
            if k > mx:
                mx, mcmc = k, cmc
            prof[ch] = (tot + k * n, mx, mcmc)
    return prof


def land_sources(d: Data, lands: dict) -> dict:
    """某套地能提供多少“色源”（非基本地按产色算；任意色地算全主色）。"""
    src = {}
    for nm, cnt in lands.items():
        if nm in BASICS:
            ch = BASIC_COLOR.get(nm)
            if ch:
                src[ch] = src.get(ch, 0) + cnt
            continue
        pc = land_produced_colors(d, nm)
        if pc is None:
            for ch in ALL_COLORS:
                src[ch] = src.get(ch, 0) + cnt
        elif pc != "unknown":
            for ch in pc:
                src[ch] = src.get(ch, 0) + cnt
    return src


def cast_probs(d: Data, chosen, lands: dict) -> dict:
    """每张牌在 `cmc` 回合前能凑齐其有色符号的概率（超几何近似）。"""
    src, pop = land_sources(d, lands), 40
    out = {}
    for nm, n in chosen.items():
        if nm in BASICS or is_land(d, nm):
            continue
        draws = max(1, min(pop, 7 + max(int(round(d.cmc(nm) or 1)), 1) - 1))
        cnt = {}
        for sym in re.findall(r"\{([^}]+)\}", d.mana_cost(nm) or ""):
            if "/" in sym:
                continue
            for ch in sym:
                if ch in ALL_COLORS:
                    cnt[ch] = cnt.get(ch, 0) + 1
        p = 1.0
        for ch, k in cnt.items():
            p *= _hyper_ge(src.get(ch, 0), draws, pop, k)
        out[nm] = p
    return out


def spell_pips(d: Data, chosen) -> dict:
    """选入咒语的色符计数（跳过 hybrid/phyrexian），用于分摊基本地。"""
    out = {}
    for nm, n in chosen.items():
        for sym in re.findall(r"\{([^}]+)\}", d.mana_cost(nm) or ""):
            if "/" in sym:
                continue
            for ch in sym:
                if ch in ALL_COLORS:
                    out[ch] = out.get(ch, 0) + n
    return out


def commit_pair(d: Data, have: dict, committed=None, min_pool: int = 12):
    """已承诺的色组：显式给定，或牌池够大时取拟合最高的 archetype。"""
    if committed:
        return str(committed).upper()[:3]
    if sum(have.values()) < min_pool:
        return None
    fits = {s: archetype_fit(d, s, have) for s in d.main}
    if not fits:
        return None
    slug = max(fits, key=lambda s: fits[s])
    t = d.templates[slug]
    return (t.get("colors") or t["archetype"]).upper()


def commit_arch(d: Data, have: dict, committed=None, min_pool: int = 12):
    """已承诺的 slug：committed 可以是色组串也可以是 slug；否则取拟合最高。"""
    if committed:
        if committed in d.main:
            return committed
        c = str(committed).upper()[:3]
        for s, t in d.templates.items():
            if (t.get("colors") or t["archetype"]).upper() == c:
                return s
    if sum(have.values()) < min_pool:
        return None
    fits = {s: archetype_fit(d, s, have) for s in d.main}
    return max(fits, key=lambda s: fits[s]) if fits else None


def creature_gap(d: Data, have: dict, t: dict):
    """“缺啥补啥”：**相对“按比例继续抓”的偏离**，并归一化。

    natural = ratio · 当前咒语数   # 若之后每抓都按 ratio 出生物，最终会有的生物数
    gap     = (natural − 当前生物数) / CRE_DIV
      + = 生物少了（该补生物），- = 生物多了（该补非生物），0 = 正好按比例。
    分子就是“还缺几只”，分母 CRE_DIV 控制力度（越小越狠）；高于比例线时自动转负 → 不过冲。
    """
    ratio = float((t.get("deck_params") or {}).get("creature_ratio") or 0.55)
    poolc = [nm for nm in have
             if nm not in BASICS and not is_land(d, nm) and color_fit(d, nm, t) > 0]
    n_all = sum(have[nm] for nm in poolc)
    if n_all < 6:
        return 0.0
    n_cre = sum(have[nm] for nm in poolc if is_creature(d, nm))
    gap = (ratio * n_all - n_cre) / CRE_DIV
    return max(-1.0, min(1.0, gap))


def score_cards(d: Data, cards, have: dict, committed=None, ctx=None):
    fits = {slug: archetype_fit(d, slug, have) for slug in d.main}
    # ctx["locked"]：从 LOCK_FROM_PICK 起锁死的 slug；锁死后其它思路权重归 0（硬锁）。
    locked = (ctx or {}).get("locked")
    if locked in d.main:
        weights = {s: (1.0 if s == locked else 0.0) for s in d.main}
    else:
        weights = archetype_weights(d, fits)
    carch = locked if locked in d.main else commit_arch(d, have, committed)
    cre_lvl = creature_gap(d, have, d.templates[carch]) if carch else 0.0
    if carch:
        _ct = d.templates[carch]
        c_main = set((_ct.get("archetype") or "").upper())
        c_full = set((_ct.get("colors") or _ct["archetype"]).upper())
    else:
        c_main = c_full = set()
    n_pool = sum(have.values())
    # 进度因子：牌池越大越接近“最后要交的那一副牌”。同时驱动三件事：
    #   ① color_fit 介入 u 的程度（早期不卡颜色，后期只算能打出来的）
    #   ② 颜色奖惩的力度
    #   ③ 超过 23 张后的额外加码（COLOR_LATE）
    prog = min(1.0, n_pool / COLOR_RAMP)
    if n_pool > 23 and COLOR_LATE:
        prog *= 1.0 + COLOR_LATE * (n_pool - 23) / 19.0
    # 颜色开放度信号（只在给了 pick 位置时启用；后期淡出但不归零）
    # 用**包内抓位**（1..14）跟 ALSA 比：ALSA 是包内的平均抓位，不是全局 1..42。
    # 否则 pack2/3 的 late 整体 +14，openness 会变成“哪张牌 ALSA 小”。
    _pi = (ctx.get("pick_index") or 0) if ctx else 0
    _pp = (ctx.get("pack_pick") if ctx else None)
    if _pp is None:
        _pp = ((_pi - 1) % 14 + 1) if _pi else 0
    openness = color_openness(d, cards, _pp) if ctx else {}
    # 与 color 相位互补：前期看“包在传什么色”，定色后交给 color 项（open→0），不重复叠加
    op_w = W_OPEN * max(0.0, 1.0 - min(1.0, prog))
    scored = []
    _names = [d.name_of(it) for it in (cards or [])]
    _has_nonbasic = any(nm not in BASICS for nm in _names)
    for item in cards or []:
        nm = d.name_of(item)
        if nm in BASICS:
            if _has_nonbasic:
                # 包里还有真牌 → 基本地不参与选牌，也不列进包/分项
                continue
            # 整包只剩基本地（尾包）→ 保留占位，避免上游数量/排序拿到空列表
            scored.append({"name": nm, "score": -1000.0, "value": 0.0, "archetype": None})
            continue
        total, best = 0.0, None
        decomp = {k: 0.0 for k in _UKEYS}
        pkg = W_PKG * package_with_pool(d, nm, have)      # 与思路无关，算一次
        for slug in d.main:
            t = d.templates[slug]
            w = weights.get(slug, 0.0)
            cf = color_fit(d, nm, t)
            # 越往后越只用“这个思路里打得出这张牌”的分量参与加权
            cf_eff = 1.0 - prog * (1.0 - cf)
            buckets = curve_have(d, have, t)
            ucs = u_components(d, nm, t, have, buckets)
            ucs["package"] = pkg                          # 全局项，覆盖上面的重复计算
            # 质量（gih）是**牌自身**的属性：不随思路/颜色打折，单独作为全局项（见下）
            u = cf_eff * sum(v for k, v in ucs.items() if k != "gih")
            total += w * u
            if w:
                # 真正参与 score 的分量贡献（跨思路加权 × 颜色可打性）
                for k, v in ucs.items():
                    if k == "gih":
                        continue
                    decomp[k] += w * cf_eff * v
            # card_best_archetype 只看**能打的思路**：card_value 不看颜色，
            # 否则一个纯蓝牌会因“RG 的 4 费桶正好空着”而被算成 RG 的最佳牌。
            if cf > 0 and (best is None or u > best[0]):
                best = (u, slug, ucs)
        # 质量项：全场 GIH/IWD（与思路无关，不打折）
        _cc = (d.templates[carch]["_cardmap"].get(nm) if carch else None)
        gih_term = W_GIH * base_gih(d, nm, _cc) * 100
        total += gih_term
        decomp["gih"] = gih_term
        # —— 下面三个项不进 u_components，但也算进 score；单独列 bucket——
        color_term = 0.0
        if carch and nm not in BASICS and not is_land(d, nm):
            hard, ors = d.req(nm)
            if not hard and not ors:
                pass                                    # 无色牌：中性
            else:
                if colors_ok(hard, ors, c_main):
                    _bin = COLOR_IN_BONUS * W_COLOR * prog          # 主色内
                elif colors_ok(hard, ors, c_full):
                    _bin = 0.0                                      # splash：中性
                else:
                    _roles = (d.templates[carch]["_cardmap"].get(nm) or {}).get("roles") or []
                    _gih = (d.cdata.get(nm) or {}).get("ever_drawn_win_rate") or 0.0
                    _mult = 1.0 if ("bomb" in _roles or _gih >= 0.58) else 2.0
                    _bin = -_mult * W_COLOR * prog                  # 离色
                if COLOR_SOFT > 0:
                    # 软化：按“跨思路加权的颜色契合”混合（RG 很开时绿牌少罚）
                    cf_w = sum(w * color_fit(d, nm, d.templates[s2]) for s2, w in weights.items())
                    _soft = W_COLOR * prog * (2.0 * cf_w - 1.0)
                    color_term = (1.0 - COLOR_SOFT) * _bin + COLOR_SOFT * _soft
                else:
                    color_term = _bin
        cre_term = 0.0
        if cre_lvl and nm not in BASICS and not is_land(d, nm):
            cre_term = W_CRE * cre_lvl if is_creature(d, nm) else -W_CRE * cre_lvl
        open_term = 0.0
        if openness and nm not in BASICS and not is_land(d, nm):
            open_term = op_w * card_openness(d, nm, openness)
        total += color_term + cre_term + open_term
        decomp["color"] = color_term
        decomp["cre"] = cre_term
        decomp["open"] = open_term
        comps = dict(best[2]) if best else {}
        comps["openness"] = round(open_term, 3)
        # 分项表要求“显示值相加 = score”：统一按 2 位小数，且 score 直接取分项之和
        decomp = {k: round(v, 2) for k, v in decomp.items()}
        total = round(sum(decomp.values()), 2)
        scored.append({"name": nm, "score": total,
                       "value": round(best[0], 3) if best else 0.0,
                       "archetype": best[1] if best else None,
                       "decomp": decomp,
                       "components": ({k: round(v, 3) for k, v in comps.items()}
                                      if comps else None)})
    scored.sort(key=lambda r: -r["score"])
    return scored, fits, weights


# ---------------------------------------------------------------- pick
def check_names(d: Data, st: dict) -> None:
    """校验 pack / pool 里的牌名。未识别的牌不能默认给分：
    color_fit 会返回 1.0、cmc 当 0 归到 1 费桶，凭空拿到一个“虚拟分”，
    甚至能顶掉真实的最优牌。所以直接报错退出（exit 2），并给出近名提示。"""
    names = [d.name_of(c) for c in (st.get("pack") or [])]
    names += [d.name_of(c) for c in (st.get("pool") or [])]
    bad = d.unknown(names)
    if not bad:
        return
    known = sorted(d.known_names())
    hints = []
    for nm in bad[:6]:
        near = difflib.get_close_matches(nm, known, n=2, cutoff=0.6)
        hints.append("%s%s" % (nm, ("（是不是 %s ？）" % " / ".join(near)) if near else ""))
    die(2, "无法识别的牌：%s" % "；".join(hints))


def cmd_pick(d: Data, st: dict, fmt: str, explain: bool = False) -> int:
    pack = st.get("pack") or []
    if not pack:
        die(2, "state.pack 为空")
    check_names(d, st)
    have = pool_counts(st.get("pool"))
    committed = st.get("colors")
    pn, pk = st.get("pack_number"), st.get("pick_number")
    pi = (pn - 1) * 14 + pk if isinstance(pn, int) and isinstance(pk, int) else None
    locked = st.get("locked")
    if LOCK_FROM_PICK > 0 and not locked and pi and pi >= LOCK_FROM_PICK:
        locked = commit_arch(d, have, committed)      # 锁死思路（默认关）
    ctx = {"pick_index": pi, "locked": locked}
    scored, fits, weights = score_cards(d, pack, have, committed, ctx)
    if not explain:
        for r in scored:
            r.pop("components", None)
            r.pop("decomp", None)
    top = scored[0]
    # the archetype you're heading into = highest fitted (not the card's own best fit)
    cur = committed or (max(fits, key=lambda s: fits[s]) if fits else None)
    order = sorted(fits.items(), key=lambda kv: -kv[1])[:5]
    advice = []
    if not have:
        advice.append("首抓：牌池为空，直接按卡片绝对质量取最高的那张。")
    else:
        advice.append(f"当前牌池 {sum(have.values())} 张；最贴合的是 {d.templates[cur]['archetype_name']}（fit {fits[cur]:.1f}）。")
    if len(order) > 1 and order[0][1] - order[1][1] < 3:
        advice.append("前两名拟合度接近，可以再观察一两个包。")
    out = {
        "snapshot": d.snap, "command": "pick",
        "state": {"pack_size": len(pack), "pool_size": sum(have.values()), "colors": committed},
        "recommendation": {"name": top["name"], "score": top["score"],
                           "archetype": cur,
                           "archetype_name": d.templates[cur]["archetype_name"],
                           "card_best_archetype": top["archetype"]},
        "scores": scored,
        "archetypes": [{"slug": s, "name": d.templates[s]["archetype_name"],
                        "colors": d.templates[s].get("colors") or d.templates[s]["archetype"],
                        "fit": round(f, 3), "weight": round(weights.get(s, 0.0), 3)}
                       for s, f in sorted(fits.items(), key=lambda kv: -kv[1])],
        "advice": advice,
    }
    emit(out, fmt)
    return 0


# ---------------------------------------------------------------- build
def cmd_build(d: Data, st: dict, fmt: str) -> int:
    check_names(d, st)
    have = pool_counts(st.get("pool"))
    if sum(have.values()) < 23:
        die(2, f"牌池只有 {sum(have.values())} 张，不足 23 张咒语")
    emit(build_deck(d, have, st.get("archetype")), fmt)
    return 0


def build_deck(d: Data, have: dict, want_slug=None) -> dict:
    """把牌池配成 40 张（曲线优先贪心）。可被其它脚本直接调用。"""
    fits = {slug: archetype_fit(d, slug, have) for slug in d.main}
    slug = want_slug
    if slug not in d.main:
        slug = max(d.main, key=lambda s: fits[s], default=None)
    if slug is None:
        die(3, "没有可用的 archetype 模板")
    t = d.templates[slug]
    pair = (t.get("colors") or t["archetype"]).upper()
    dp = t.get("deck_params") or {}
    targets = target_curve(d, t)
    # 生物比例：向 archetype 靠拢，硬约束 ±10%（相对目标张数，23 张 × 56% ≈ ±1.3 张）
    want_cre = float(dp.get("creature_ratio") or 0.55) * 23.0
    cre_tol = want_cre * CRE_TOL

    cand = [nm for nm, n in have.items()
            if nm not in BASICS and not is_land(d, nm) and color_fit(d, nm, t) > 0]
    cand.sort(key=lambda nm: -card_value(d, nm, t))

    # 1) 曲线配额优先：目标曲线（基线 2/7/6/4/3/1 + 本 stream 实测浮动）化成整数配额，
    #    每个费用桶按「卡值 + 生物缺口」取最好的若干张。以前是「全局按卡值排序、
    #    桶只当上限」，结果 2 费永远被优先堆满，曲线失控。
    quota = int_quota(targets)
    by_b = {}
    for nm in cand:
        by_b.setdefault(curve_bucket(d.cmc(nm)), []).append(nm)
    chosen, buckets = Counter(), {k: 0 for k, _ in CURVE}
    avail = {nm: have[nm] for nm in cand}          # 还能再拿几张
    # 模板给的同名张数区间（实测）：max = 该思路单副最多带几张，min = 核心牌表的标配
    cap = {}
    floor = {}
    for nm in avail:
        c = t["_cardmap"].get(nm)
        cap[nm] = max(1, int((c or {}).get("max_copies") or 1)) if c else avail[nm]
        floor[nm] = int((c or {}).get("min_copies") or 0) if c else 0
    used = n_cre = 0

    def can(nm):
        return avail.get(nm, 0) > 0

    def over_cap(nm):
        """超出该思路实测上限的张数。**软惩罚**，不是硬限制——
        牌池薄（日志残缺/同名牌扎堆）时必须允许超，否则凑不出 23 张咒语。"""
        return max(0, chosen.get(nm, 0) + 1 - cap.get(nm, 99))

    def cre_gap(nm):
        """生物缺口（带符号）：偏离 archetype 目标越远拉得越狠。"""
        c = is_creature(d, nm)
        if c:
            return 1.0 if n_cre < want_cre - cre_tol else (0.3 if n_cre < want_cre else -1.0)
        return 1.0 if n_cre > want_cre + cre_tol else (0.3 if n_cre > want_cre else -1.0)

    def staple(nm):
        """该思路的标配牌（min_copies=1）还没拿到 → 加分。"""
        return W_MIN if floor.get(nm, 0) > chosen.get(nm, 0) else 0.0

    def take(nm, k=1):
        nonlocal used, n_cre
        k = min(k, avail.get(nm, 0))
        if k <= 0:
            return 0
        chosen[nm] += k
        avail[nm] -= k
        buckets[curve_bucket(d.cmc(nm))] += k
        used += k
        if is_creature(d, nm):
            n_cre += k
        return k

    def drop(nm):
        nonlocal used, n_cre
        chosen[nm] -= 1
        if chosen[nm] <= 0:
            del chosen[nm]
        avail[nm] = avail.get(nm, 0) + 1
        buckets[curve_bucket(d.cmc(nm))] -= 1
        used -= 1                                  # 少了这句：交换后 used 虚高、地数配错
        if is_creature(d, nm):
            n_cre -= 1

    for b, _fn in CURVE:
        got = 0
        while got < quota.get(b, 0) and used < 23:
            pick = [nm for nm in by_b.get(b, []) if can(nm)]
            if not pick:
                break
            take(max(pick, key=lambda x: card_value(d, x, t) + W_CRE * cre_gap(x) + staple(x) + pool_extra(d, x, t, chosen)
                     - W_SAT * over_cap(x)))
            got += 1
    # 2) 没填满：按「卡值 + 曲线缺口 + 生物缺口 + 标配」补
    while used < 23:
        pick = [nm for nm in cand if can(nm)]
        if not pick:
            break
        take(max(pick, key=lambda x: card_value(d, x, t)
                 + W_CURVE * curve_need(d, x, t, buckets) + W_CRE * cre_gap(x) + staple(x) + pool_extra(d, x, t, chosen)
                 - W_SAT * over_cap(x)))
    # 2b) 同色还不够 23 张 → 放宽到任意颜色（硬凑/临时 splash），保证出得来 40
    while used < 23:
        pick = [nm for nm, n in have.items()
                if can(nm) and nm not in BASICS and not is_land(d, nm)]
        if not pick:
            break
        take(max(pick, key=lambda x: card_value(d, x, t) + W_CRE * cre_gap(x) + staple(x) + pool_extra(d, x, t, chosen)
                 - W_SAT * over_cap(x)))

    # 3) 生物比例硬约束：超出 ±10% 就在同费用桶里换牌（尽量不破坏曲线）
    for _ in range(40):
        if want_cre - cre_tol <= n_cre <= want_cre + cre_tol:
            break
        more = n_cre < want_cre - cre_tol
        outs = sorted([nm for nm in chosen if is_creature(d, nm) != more],
                      key=lambda nm: card_value(d, nm, t))
        swapped = False
        for out in outs:
            b = curve_bucket(d.cmc(out))
            ins = [nm for nm in cand if can(nm) and is_creature(d, nm) == more
                   and curve_bucket(d.cmc(nm)) == b]
            if not ins:                            # 同费用桶没牌 → 放宽到任意费用
                ins = [nm for nm in cand if can(nm) and is_creature(d, nm) == more]
            if not ins:
                break
            best = max(ins, key=lambda x: card_value(d, x, t))
            if card_value(d, best, t) < card_value(d, out, t) - CRE_SWAP_MAX:
                break                              # 不为凑比例拆掉太好的牌
            drop(out)
            take(best)
            swapped = True
            break
        if not swapped:
            break

    # 3) 地：优先用池子里的非基本地，其余基本地按“实际选入咒语的色符数”分摊
    # 地数 = 40 − 咒语数，保证总数恒为 40（牌池凑不够 23 咒语时地数会多于 17，
    # 那是牌池本身的问题，调用方应看咒语数）；land_count 只用作兜底下限参考。
    nlands = max(int(round(float(dp.get("land_count") or 17))), min(40, 40 - used))
    pips = spell_pips(d, chosen)
    if not pips:                                   # 全是无色牌的极端情况：退回模板分布
        for nm, n in (dp.get("basic_lands") or {}).items():
            ch = BASIC_COLOR.get(nm)
            if ch:
                pips[ch] = pips.get(ch, 0) + n
        if not pips:
            pips = {ch: 1 for ch in (pair or "U")[:2]}
    # 非基本地：**先按能不能产本套需要的色过滤**（否则会把 {B}/{G}、{C} 地塞进 UR），
    # 再按簇内包含率、池里张数排序；最多 3 张，其余用基本地。
    need = set(pips)
    nonbasic = [nm for nm in have
                if is_land(d, nm) and nm not in BASICS and _land_helps(d, nm, need)]
    nonbasic.sort(key=lambda nm: (-_land_fit(d, nm, t), -have.get(nm, 0)))
    lands = {}
    for nm in nonbasic[:3]:
        lands[nm] = lands.get(nm, 0) + 1
    left = max(0, nlands - sum(lands.values()))
    prof = mana_profile(d, chosen)
    main = set(pair) & set(pips)
    if not main:
        main = set(sorted(pips, key=lambda k: -pips[k])[:2])
    src = land_sources(d, lands)
    req = {}
    for ch in main:
        _tot, mx, mcmc = prof.get(ch, (pips.get(ch, 0), 1, 3))
        req[ch] = sources_needed(mx, mcmc, 0.90)
    # 可行（主色缺额之和 ≤ 剩余基本地）→ 超几何把每个主色喂够；不可行 → 退回按色符比例
    if sum(max(0, req[ch] - src.get(ch, 0)) for ch in main) <= left:
        for ch in sorted(req, key=lambda c: -(req[c] - src.get(c, 0))):
            v = min(max(0, req[ch] - src.get(ch, 0)), left)
            if v > 0:
                lands[COLOR_BASIC[ch]] = lands.get(COLOR_BASIC[ch], 0) + v
                left -= v
    base = {c: pips.get(c, 0) for c in (main or pips)} or dict(pips)
    tot_p = sum(base.values()) or 1
    acc = 0
    keys = sorted(base, key=lambda k: -base[k])
    for i, ch in enumerate(keys):
        v = (left - acc) if i == len(keys) - 1 else min(int(round(base[ch] / tot_p * left)), left - acc)
        if v > 0:
            lands[COLOR_BASIC[ch]] = lands.get(COLOR_BASIC[ch], 0) + v
        acc += v
    short = nlands - sum(lands.values())
    if short > 0 and keys:
        lands[COLOR_BASIC[keys[0]]] = lands.get(COLOR_BASIC[keys[0]], 0) + short
    # 法力一致性：每张牌“按期凑齐有色符号”的概率（低支持度应虑换掉）
    probs = cast_probs(d, chosen, lands)
    weak = sorted(((nm, round(p, 2)) for nm, p in probs.items() if p < 0.80),
                  key=lambda x: x[1])

    spells = [{"count": n, "name": nm, "value": round(card_value(d, nm, t), 2)}
              for nm, n in sorted(chosen.items(), key=lambda kv: -card_value(d, kv[0], t))]
    mtga = "\n".join(["Deck"] + [f"{s['count']} {s['name']}" for s in spells]
                     + [f"{v} {k}" for k, v in sorted(lands.items(), key=lambda kv: -kv[1])])
    ncre = n_cre
    adv_build = ("按曲线配额配牌；生物 %d 张（该思路目标约 %d 张）" % (ncre, round(want_cre)))
    _warn = []
    if used < 23:
        _warn.append("牌池只有 %d 张可打的咒语，不足 23 张，多出来的位置用地补满" % used)
    if not (want_cre - cre_tol <= ncre <= want_cre + cre_tol):
        _warn.append("生物比例偏离该思路目标超过 ±%d%%（牌池里没有足够的生物可以换）" % round(CRE_TOL * 100))
    adv_build += "。" + ("⚠️ " + "；".join(_warn) + "。" if _warn else "")
    if weak:
        adv_build += "；低支持度（<80% 按期可施放）：" + "、".join(
            "%s %.0f%%" % (nm, p * 100) for nm, p in weak[:4]) + "。"
    # 备牌：牌池里没进主牌的（按卡值降序）
    side = [{"count": n, "name": nm, "value": round(card_value(d, nm, t), 2)}
            for nm, n in sorted(have.items(), key=lambda kv: -card_value(d, kv[0], t))
            if nm not in chosen and nm not in BASICS and not is_land(d, nm)]
    out = {
        "snapshot": d.snap, "command": "build",
        "archetype": {"slug": slug, "name": t["archetype_name"], "colors": pair, "fit": round(fits[slug], 3)},
        "deck": {"spells": spells, "lands": lands,
                 "total_spells": sum(s["count"] for s in spells),
                 "total_lands": sum(lands.values()), "n_creatures": ncre,
                 "mana_weak": weak, "sideboard": side,
                 "mtga": mtga},
        "advice": [adv_build,
                   "如果想要更强上限，可对照 reference_decks/<slug>.mtga.txt 的 medoid 牌表做替换。"],
    }
    return out


def cmd_archetypes(d: Data, st: dict, fmt: str) -> int:
    check_names(d, st)
    have = pool_counts((st or {}).get("pool"))
    fits = {slug: archetype_fit(d, slug, have) for slug in d.main}
    out = {"snapshot": d.snap, "command": "archetypes", "pool_size": sum(have.values()),
           "archetypes": [{"slug": s, "name": d.templates[s]["archetype_name"],
                           "colors": d.templates[s].get("colors") or d.templates[s]["archetype"],
                           "fit": round(f, 3)}
                          for s, f in sorted(fits.items(), key=lambda kv: -kv[1])]}
    emit(out, fmt)
    return 0


def cmd_check(d: Data, st, fmt: str) -> int:
    out = {"snapshot": d.snap, "command": "check",
           "templates": len(d.templates), "reference_decks": len(d.refs),
           "cards": len(d.cdata),
           "missing": [s for s in d.index if s not in d.templates]}
    emit(out, fmt)
    return 0 if not out["missing"] else 3


def emit(obj: dict, fmt: str) -> None:
    if fmt == "text":
        if obj.get("command") == "pick" and obj.get("recommendation"):
            print(f"建议抓：{obj['recommendation']['name']}  "
                  f"（{obj['recommendation']['archetype_name']}，score {obj['recommendation']['score']}）")
            for r in obj.get("scores", [])[:5]:
                print(f"  {r['score']:>7.2f}  {r['name']}")
                _dc = r.get("decomp") or r.get("components")
                if _dc:
                    print("           " + "  ".join("%s%+.2f" % (k, v)
                                                  for k, v in _dc.items()))
            for a in obj.get("advice", []):
                print(f"  · {a}")
            return
        if obj.get("command") == "build":
            print(obj["deck"]["mtga"])
            return
    print(json.dumps(obj, ensure_ascii=False, indent=1))


# ---------------------------------------------------------------- main
def main() -> int:
    ap = argparse.ArgumentParser(description="FRA Premier Draft 抓牌/配牌引擎")
    ap.add_argument("command", choices=["pick", "build", "archetypes", "check"])
    ap.add_argument("--snapshot", default=DEFAULT_SNAP)
    ap.add_argument("--state", default="-", help="state.json 路径，或 - 读 stdin")
    ap.add_argument("--format", choices=["json", "text"], default="json")
    ap.add_argument("--explain", action="store_true",
                    help="pick: 每张牌列出命名分项（gih/affinity/synergy/curve/role/…）")
    a = ap.parse_args()

    st = {}
    if a.state and a.state != "-":
        p = Path(a.state)
        if not p.exists():
            die(2, f"找不到 state 文件：{p}")
        st = json.loads(p.read_text(encoding="utf-8"))
    elif not sys.stdin.isatty():
        raw = sys.stdin.read().strip()
        st = json.loads(raw) if raw else {}
    if st is None:
        st = {}

    d = Data(a.snapshot)
    if a.command == "pick":
        return cmd_pick(d, st, a.format, a.explain)
    return {"build": cmd_build, "archetypes": cmd_archetypes,
            "check": cmd_check}[a.command](d, st, a.format)


if __name__ == "__main__":
    raise SystemExit(main())
