import argparse
import json
import sys
import time

import numpy as np
import torch


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--model", required=True)
    p.add_argument("--depths", type=int, nargs="+", default=[1, 2, 3, 4, 5, 6])
    p.add_argument("--trials", type=int, default=8)
    p.add_argument("--beams", type=int, nargs="+", default=[1, 8, 32])
    p.add_argument("--expand", type=int, default=4)
    p.add_argument("--budget", type=float, default=2.0)
    p.add_argument("--seed", type=int, default=20260913)
    p.add_argument("--out", default="beam_lora_results.json")
    return p.parse_args()


def main():
    args = parse_args()
    sys.path.insert(0, "src")
    import cube
    import motor_pools
    from lif_gpu import Connectome
    from lif_train import TrainableBrain

    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    device = "cuda:0"
    torch.cuda.set_device(0)

    lora = torch.load(args.model, map_location="cpu", weights_only=False)
    base = torch.load(lora["base_ckpt"], map_location="cpu", weights_only=False)
    base_args = lora["base_args"]
    rank = int(lora["args"]["rank"])
    alpha = float(lora["args"]["alpha"])
    warmup = int(lora["args"]["warmup"])
    window = int(lora["args"]["window"])

    conn = Connectome("data/npy")
    pop = conn.select(superclass="visual_projection")
    groups = np.array_split(np.arange(len(pop)), 54 * 6)
    chan = torch.as_tensor(
        np.concatenate([[c] * len(g) for c, g in enumerate(groups)]),
        device=device,
        dtype=torch.int64,
    )
    drive = pop[np.concatenate(groups)]
    mn_idx, pool_of, _ = motor_pools.build_front()
    probe = torch.as_tensor(mn_idx, device=device, dtype=torch.int64)
    pool_t = torch.as_tensor(pool_of, device=device, dtype=torch.int64)
    pool_n = torch.zeros(18, device=device).index_add_(
        0, pool_t, torch.ones(len(pool_of), device=device)
    ).clamp(min=1)
    temp = lora["temp"].to(device)

    class LoRABrain(TrainableBrain):
        def __init__(self, *brain_args, rank=4, alpha=1.0, **kwargs):
            super().__init__(*brain_args, **kwargs)
            self.base_log_mag = torch.nn.Parameter(
                self.log_mag.detach().clone(), requires_grad=False
            )
            self.log_mag.requires_grad_(False)
            self.rank = rank
            self.alpha = alpha
            self.A = torch.nn.Parameter(
                torch.zeros(self.n, rank, device=self.device), requires_grad=False
            )
            self.B = torch.nn.Parameter(
                torch.zeros(self.n, rank, device=self.device), requires_grad=False
            )

        def weights(self):
            delta = (self.A[self.tgt] * self.B[self.src]).sum(1)
            delta = delta * (self.alpha / self.rank)
            return torch.exp(self.base_log_mag + delta) * self.sign

    rng = np.random.default_rng(args.seed)
    starts = {d: cube.scramble(args.trials, d, rng)[0] for d in args.depths}
    all_results = {
        "model": args.model,
        "depths": args.depths,
        "trials": args.trials,
        "beams": args.beams,
        "expand": args.expand,
        "budget": args.budget,
        "seed": args.seed,
        "warmup": warmup,
        "window": window,
        "results": {},
    }

    for width in args.beams:
        batch = args.trials * width
        brain = LoRABrain(
            conn,
            batch,
            device=device,
            seed=1,
            slope=base_args["slope"],
            shuffle=base_args.get("shuffle"),
            rank=rank,
            alpha=alpha,
        )
        brain.set_drive(drive)
        with torch.no_grad():
            brain.base_log_mag.copy_(base["log_mag"].to(device))
            brain.A.copy_(lora["A"].to(device))
            brain.B.copy_(lora["B"].to(device))

        @torch.inference_mode()
        def logprobs(states):
            oh = torch.as_tensor(cube.onehot(states), device=device)
            rates = (oh[:, chan] * base_args["rate"]).T.contiguous()
            counts = brain(
                rates,
                warmup=warmup,
                window=window,
                probe=probe,
                graded=bool(base_args.get("graded", 1)),
            )
            scores = torch.zeros(18, counts.shape[1], device=device).index_add_(
                0, pool_t, counts
            )
            logits = (scores / pool_n[:, None]).T * temp
            return torch.log_softmax(logits, 1).cpu().numpy()

        width_results = {}
        for depth in args.depths:
            start = starts[depth]
            beams = np.repeat(start[:, None, :], width, axis=1)
            score = np.full((args.trials, width), -np.inf, dtype=np.float64)
            score[:, 0] = 0.0
            done = (start == cube.SOLVED).all(1)
            steps = np.full(args.trials, -1, dtype=int)
            t0 = time.time()
            max_steps = int(round(args.budget * depth))

            for step in range(max_steps):
                if done.all():
                    break
                lp = logprobs(beams.reshape(-1, 54)).reshape(
                    args.trials, width, cube.N_MOVES
                )
                expand = 1 if width == 1 else min(args.expand, cube.N_MOVES)
                top = np.argsort(-lp, axis=2)[:, :, :expand]
                cand_score = score[:, :, None] + np.take_along_axis(lp, top, axis=2)
                next_states = cube.apply_move(
                    np.repeat(beams.reshape(-1, 54), expand, axis=0),
                    top.reshape(-1),
                ).reshape(args.trials, width * expand, 54)
                flat_score = cand_score.reshape(args.trials, width * expand)
                hit = (next_states == cube.SOLVED).all(2)
                newly = hit.any(1) & ~done
                steps[newly] = step + 1
                done |= hit.any(1)
                order = np.argsort(-flat_score, axis=1)[:, :width]
                beams = np.take_along_axis(next_states, order[:, :, None], axis=1)
                score = np.take_along_axis(flat_score, order, axis=1)
                beams[done] = cube.SOLVED
                score[done] = 0.0

            elapsed = time.time() - t0
            solved_steps = steps[steps > 0]
            result = {
                "solved": int(done.sum()),
                "trials": args.trials,
                "rate": float(done.mean()),
                "avg_steps": float(solved_steps.mean()) if len(solved_steps) else None,
                "seconds": elapsed,
            }
            width_results[str(depth)] = result
            print(
                f"beam={width:>2} depth={depth} solved={done.sum()}/{args.trials} "
                f"rate={done.mean():.1%} sec={elapsed:.1f}",
                flush=True,
            )
        all_results["results"][str(width)] = width_results
        del brain
        torch.cuda.empty_cache()

    with open(args.out, "w") as f:
        json.dump(all_results, f, indent=2)
    print(f"saved {args.out}", flush=True)


if __name__ == "__main__":
    main()
