"""E147 research agent: the E145 active-identification agent with switchable mechanisms ("genes").

A config = the E145 parameters (w_ig, w_split, w_novel, eps, stop) + three genes:

* ``noise``  : "fixed" (assume eps, as E145) | "mixture" (joint posterior over the hypothesis and a noise level in
               EPS_GRID; marginal over noise for decisions)
* ``stopper``: "threshold" (stop when max posterior >= stop, as E145) | "voi" (stop when the best experiment's
               expected gain in P(correct) is below voi_scale x the per-experiment cost 0.3 / budget)
* ``repeat`` : 0 | 1 (if 1, the 4 previously asked queries whose outcomes are most uncertain under the current
               posterior replace 4 random candidates; lets a noisy agent re-test)

Compute is fixed per decision: at most BUDGET_EVALS = 32 x |H| hypothesis-evaluations. The mixture costs |EPS_GRID|
evaluations per hypothesis, so it scores floor(32 / 3) = 10 candidates instead of 32. The improver must trade.

With genes (fixed, threshold, 0) the agent is the E145 agent: tests check identical decisions.
"""
from __future__ import annotations

import itertools
import math

import numpy as np

from e145.families import _hy_eval, _hy_rules

EPS_GRID = (0.03, 0.12, 0.25)
N_CAND = 32
PARAMS = {"w_ig": (0.0, 2.0), "w_split": (0.0, 2.0), "w_novel": (0.0, 2.0), "eps": (0.01, 0.4), "stop": (0.6, 0.999),
          "voi_scale": (0.2, 3.0)}
GENES = {"noise": ("fixed", "mixture"), "stopper": ("threshold", "voi"), "repeat": (0, 1)}
G0 = {"w_ig": 1.0, "w_split": 0.0, "w_novel": 0.0, "eps": 0.05, "stop": 0.95, "voi_scale": 1.0,
      "noise": "fixed", "stopper": "threshold", "repeat": 0, "n_cand": N_CAND}


def clip(cfg: dict) -> dict:
    out = {k: round(float(min(hi, max(lo, cfg[k]))), 6) for k, (lo, hi) in PARAMS.items()}
    for g, vals in GENES.items():
        out[g] = cfg[g] if cfg[g] 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 - p) * np.log(1 - 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)
    mix = cfg.get("noise") == "mixture"
    E = np.array(EPS_GRID if mix else (min(0.45, max(0.01, cfg["eps"])),))
    logw = np.zeros((len(H), len(E)))           # joint log posterior over (hypothesis, noise level)
    n_cand = int(cfg.get("n_cand", N_CAND)) // len(E)
    asked, used = [], 0
    cost = 0.3 / budget
    for t in range(budget):
        W = np.exp(logw - logw.max()); W /= W.sum()
        wh = W.sum(1)                            # marginal over hypotheses
        if cfg.get("stopper", "threshold") == "threshold" and wh.max() >= cfg["stop"]:
            break
        m = int(min(len(X), max(1, n_cand)))
        idx = list(rng.choice(len(X), m, replace=False))
        if cfg.get("repeat") and asked:
            prev = sorted(set(asked), key=lambda j: -min(wh @ M[:, j], 1 - wh @ M[:, j]))[:4]
            idx = (prev + [j for j in idx if j not in prev])[:m]
        idx = np.array(idx)
        p1h = M[:, idx]                                          # P(y=1 | h) without noise
        q = np.einsum("he,hc->c", W * (1 - E)[None, :], p1h) + np.einsum("he,hc->c", W * E[None, :], 1 - p1h)
        # expected information about h: H(y) - E_h,e H(y | h, e)
        ig = _bh(q) - (W.sum(0) * _bh(E)).sum()
        split = np.minimum(wh @ p1h, 1 - wh @ p1h)
        nov = np.array([0.0 if not asked else min(sum(a != b for a, b in zip(X[j], X[k])) for k in asked) / max(F, 1)
                        for j in idx])
        sc = cfg["w_ig"] * ig + cfg["w_split"] * split + cfg["w_novel"] * nov + 1e-9 * rng.random(len(idx))
        jbest = int(idx[int(np.argmax(sc))])
        if cfg.get("stopper") == "voi":
            # expected P(correct) after observing the best experiment minus P(correct) now
            col = M[:, jbest]
            gain = 0.0
            for y in (0, 1):
                lik = np.where(col[:, None] == y, 1 - E[None, :], E[None, :])
                Wy = W * lik
                py = Wy.sum()
                if py > 0:
                    gain += py * (Wy.sum(1) / py).max()
            if gain - wh.max() < cfg["voi_scale"] * cost:
                break
        y = oracle(X[jbest]); asked.append(jbest); used += 1
        logw += np.log(np.where(M[:, jbest][:, None] == y, 1 - E[None, :], E[None, :]))
    best = int(np.argmax(np.exp(logw - logw.max()).sum(1)))
    if trace is not None:
        W = np.exp(logw - logw.max()); W /= W.sum()
        trace.update(used=used, conf=float(W.sum(1).max()))
    return {"h": list(H[best]), "used": used, "row": M[best].astype(int).tolist()}
