"""E148 research agent: E145/E147 active-identification agent extended with equal-compute mechanism genes.

Every configuration evaluates at most N_CAND = 32 candidates x |H| hypotheses per decision (equal compute;
no mechanism gets extra hypothesis evaluations). With G0 genes (noise_mode="fixed", query_mode="uniform",
stopper="threshold", score_mode="eig"), the agent produces decisions identical to E145/E147 G0.

Mechanism genes (general Bayesian active-learning primitives; zero domain-specific knowledge):
* ``noise_mode`` : "fixed" | "eb_online" (O(1) empirical-Bayes online noise rate estimate from observed
                   posterior disagreement, adapting cleanly from noise=0 to noise=0.35 without reducing n_cand)
                   | "tempered" (safe-Bayes likelihood tempering by eta to resist misspecified noise flips)
* ``query_mode`` : "uniform" | "repeat_uncertain" (reserves r slots of the 32-candidate pool to re-test the
                   most contested previously asked queries) | "margin_focus" (retains top-4 high-scoring queries
                   from the previous step alongside fresh random candidates, within the same n_cand=32 pool)
* ``stopper``    : "threshold" (G0: stop when max posterior >= stop) | "voi" (value-of-information stopping:
                   stop when expected gain in P(correct) < voi_scale * per-step cost) | "margin_gap" (stop only
                   after min_steps when top-1 vs top-2 posterior ratio >= stop)
* ``score_mode`` : "eig" (G0: w_ig * ig + w_split * split + w_novel * nov) | "top2_discriminate" (adds
                   w_top2 * |p(y=1|h1) - p(y=1|h2)| to prioritize crucial experiments separating the top 2
                   hypotheses)
"""
from __future__ import annotations

import itertools

import numpy as np

from e145.families import _hy_eval, _hy_rules

N_CAND = 32
PARAMS = {
    "w_ig": (0.0, 2.0),
    "w_split": (0.0, 2.0),
    "w_novel": (0.0, 2.0),
    "w_top2": (0.0, 2.5),
    "eps": (0.01, 0.40),
    "stop": (0.60, 0.999),
    "voi_scale": (0.20, 3.0),
    "eta": (0.35, 1.0),
    "eb_prior": (1.0, 8.0),
    "min_steps": (1.0, 6.0),
    "repeat_k": (1.0, 8.0),
}
GENES = {
    "noise_mode": ("fixed", "eb_online", "tempered"),
    "query_mode": ("uniform", "repeat_uncertain", "margin_focus"),
    "stopper": ("threshold", "voi", "margin_gap"),
    "score_mode": ("eig", "top2_discriminate"),
}
G0 = {
    "w_ig": 1.0,
    "w_split": 0.0,
    "w_novel": 0.0,
    "w_top2": 0.0,
    "eps": 0.05,
    "stop": 0.95,
    "voi_scale": 1.0,
    "eta": 1.0,
    "eb_prior": 4.0,
    "min_steps": 1.0,
    "repeat_k": 4.0,
    "noise_mode": "fixed",
    "query_mode": "uniform",
    "stopper": "threshold",
    "score_mode": "eig",
    "n_cand": N_CAND,
}


def clip(cfg: dict) -> dict:
    out = {k: round(float(min(hi, max(lo, cfg.get(k, G0[k])))), 6) for k, (lo, hi) in PARAMS.items()}
    for g, vals in GENES.items():
        v = cfg.get(g, G0[g])
        out[g] = v if v in vals else vals[0]
    out["n_cand"] = int(cfg.get("n_cand", N_CAND))
    return out


def _bh(p):
    return -(p * np.log(p + 1e-12) + (1.0 - p) * np.log(1.0 - p + 1e-12))


def identify(F, budget, oracle, rs, cfg, H=None, ev=None, cands=None, trace=None):
    H = H or _hy_rules(F)
    ev = ev or _hy_eval
    X = cands or [list(x) for x in itertools.product((0, 1), repeat=F)]
    rng = np.random.default_rng(rs)
    M = np.array([[ev(h, x) for x in X] for h in H], float)
    nH, nX = M.shape

    noise_mode = cfg.get("noise_mode", "fixed")
    query_mode = cfg.get("query_mode", "uniform")
    stopper = cfg.get("stopper", "threshold")
    score_mode = cfg.get("score_mode", "eig")
    n_cand = int(cfg.get("n_cand", N_CAND))
    base_eps = min(0.45, max(0.01, float(cfg.get("eps", 0.05))))
    eta = float(cfg.get("eta", 1.0)) if noise_mode == "tempered" else 1.0
    eb_prior = max(1.0, float(cfg.get("eb_prior", 4.0)))
    min_steps = int(round(float(cfg.get("min_steps", 1.0))))
    repeat_k = int(round(float(cfg.get("repeat_k", 4.0))))

    logw = np.zeros(nH, float)
    asked: list[int] = []
    obs_y: list[int] = []
    prev_top: list[int] = []
    used = 0
    cost = 0.3 / max(1, budget)
    eps_cur = base_eps

    for t in range(budget):
        w = np.exp(logw - logw.max())
        w /= w.sum()
        order_h = np.argsort(w)
        h1 = int(order_h[-1])
        h2 = int(order_h[-2]) if nH > 1 else h1
        p1, p2 = float(w[h1]), float(w[h2])

        # Stopping rule
        if stopper == "threshold":
            if p1 >= cfg["stop"]:
                break
        elif stopper == "margin_gap":
            if used >= min_steps and (p1 / max(1e-12, p1 + p2)) >= cfg["stop"]:
                break

        # Online empirical-Bayes noise update (O(t) over past queries, zero extra hypothesis evals)
        if noise_mode == "eb_online" and asked:
            # Expected disagreement of past observations under the current MAP hypothesis (and posterior)
            hist_m = M[h1, asked]
            y_arr = np.array(obs_y, float)
            disagree = float(np.sum(np.abs(hist_m - y_arr)))
            # Beta prior centered at base_eps with strength eb_prior
            alpha = eb_prior * base_eps
            beta = eb_prior * (1.0 - base_eps)
            eps_cur = min(0.42, max(0.01, (alpha + disagree) / (alpha + beta + len(asked))))
            # Re-weight logw cleanly using updated eps_cur over the short history (budget <= 20)
            if len(asked) >= 2:
                hist_M = M[:, asked]
                match = (hist_M == y_arr[None, :])
                logw = np.sum(np.where(match, np.log(1.0 - eps_cur), np.log(eps_cur)), axis=1)
                w = np.exp(logw - logw.max())
                w /= w.sum()
                order_h = np.argsort(w)
                h1 = int(order_h[-1])
                h2 = int(order_h[-2]) if nH > 1 else h1
                p1, p2 = float(w[h1]), float(w[h2])
                if stopper == "threshold" and p1 >= cfg["stop"]:
                    break
                if stopper == "margin_gap" and used >= min_steps and (p1 / max(1e-12, p1 + p2)) >= cfg["stop"]:
                    break

        m = int(min(nX, max(1, n_cand)))
        idx_list = list(rng.choice(nX, m, replace=False))
        if query_mode == "repeat_uncertain" and asked:
            # Re-test previously asked queries with highest posterior uncertainty (separates flip noise from signal)
            uniq = list(dict.fromkeys(asked))
            prev = sorted(uniq, key=lambda j: -min(float(w @ M[:, j]), 1.0 - float(w @ M[:, j])))[: min(repeat_k, m)]
            idx_list = (prev + [j for j in idx_list if j not in prev])[:m]
        elif query_mode == "margin_focus" and prev_top:
            keep = [j for j in prev_top[: min(repeat_k, m)] if j < nX]
            idx_list = (keep + [j for j in idx_list if j not in keep])[:m]
        idx = np.array(idx_list, dtype=int)

        p1h = M[:, idx]
        q_clean = w @ p1h
        q = q_clean * (1.0 - eps_cur) + (1.0 - q_clean) * eps_cur
        ig = _bh(q) - _bh(eps_cur)
        split = np.minimum(q_clean, 1.0 - q_clean)
        if cfg["w_novel"] > 0.0 and asked:
            nov = np.array([min(sum(a != b for a, b in zip(X[j], X[k])) for k in asked) / max(F, 1) for j in idx])
        else:
            nov = np.zeros(len(idx), float)

        sc = cfg["w_ig"] * ig + cfg["w_split"] * split + cfg["w_novel"] * nov
        if score_mode == "top2_discriminate":
            # Crucial-experiment term: directly separates leading hypothesis h1 from runner-up h2
            top2_sep = np.abs(M[h1, idx] - M[h2, idx])
            sc = sc + cfg.get("w_top2", 0.0) * top2_sep
        sc = sc + 1e-9 * rng.random(len(idx))

        if query_mode == "margin_focus":
            top_ord = np.argsort(-sc)[: min(4, len(idx))]
            prev_top = [int(idx[i]) for i in top_ord]

        jbest = int(idx[int(np.argmax(sc))])
        if stopper == "voi" and used >= min_steps:
            col = M[:, jbest]
            gain = 0.0
            for y in (0, 1):
                lik = np.where(col == y, 1.0 - eps_cur, eps_cur)
                wy = w * lik
                py = float(wy.sum())
                if py > 0.0:
                    gain += py * float(wy.max() / py)
            if gain - p1 < cfg["voi_scale"] * cost:
                break

        y = int(oracle(X[jbest]))
        asked.append(jbest)
        obs_y.append(y)
        used += 1
        lik_step = np.where(M[:, jbest] == y, 1.0 - eps_cur, eps_cur)
        logw = logw + eta * np.log(lik_step)

    # Final MAP prediction (with final empirical-Bayes refit if enabled)
    if noise_mode == "eb_online" and len(asked) >= 2:
        w = np.exp(logw - logw.max())
        h1 = int(np.argmax(w))
        y_arr = np.array(obs_y, float)
        disagree = float(np.sum(np.abs(M[h1, asked] - y_arr)))
        alpha = eb_prior * base_eps
        beta = eb_prior * (1.0 - base_eps)
        eps_cur = min(0.42, max(0.01, (alpha + disagree) / (alpha + beta + len(asked))))
        hist_M = M[:, asked]
        logw = np.sum(np.where(hist_M == y_arr[None, :], np.log(1.0 - eps_cur), np.log(eps_cur)), axis=1)

    best = int(np.argmax(logw))
    if trace is not None:
        w = np.exp(logw - logw.max())
        w /= w.sum()
        trace.update(used=used, conf=float(w.max()), eps_cur=round(float(eps_cur), 4))
    return {"h": list(H[best]), "used": used, "row": M[best].astype(int).tolist()}
