# legacy_test/test_vortex_lamb.py
"""Vortex Lamb — legacy test.

Builds the vortex cloaking environment with LegacyCelerisLab, loads the
vortex_lamb PPO model, runs deterministic inference (MAX_STEPS=150),
and compares against SR_analysis reference.

Usage: conda run -n pycuda_3_10 python test_vortex_lamb.py --device 0
"""

import argparse
import json
import os
import sys
import time
from collections import deque

import numpy as np

_REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
_SRC = os.path.join(_REPO, "src")
_DRL = os.path.join(_SRC, "drl_pinball")
for p in [_REPO, _SRC, _DRL]:
    if p not in sys.path:
        sys.path.insert(0, p)

from legacy_test.core.legacy_env_builder import (  # noqa: E402
    build_vortex, FIFO_LEN, CONV_LEN, U0, DATA_TYPE,
)
from legacy_test.core.model_loader import load_model  # noqa: E402
from legacy_test.core.comparator import compare_scene  # noqa: E402
from legacy_test.core.io_helpers import save_signals, save_target, save_norm  # noqa: E402

SAMPLE_INTERVAL = 800
ACTION_SCALE = 4.0
ACTION_BIAS = (0.0, -4.0, 4.0)
NUM_STEPS = 150  # MAX_STEPS for vortex
REF_DIR = os.path.join(_SRC, "SR_analysis", "data", "vortex", "vortex_lamb")
OUT_DIR = os.path.join(os.path.dirname(__file__), "output", "vortex_lamb")


def log(msg): print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--device", type=int, default=0)
    ap.add_argument("--out", type=str, default=OUT_DIR)
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)

    log("=== Vortex Lamb: Legacy Test ===")
    data = build_vortex(device_id=args.device, vortex_type="lamb",
                        action_scale=ACTION_SCALE, action_bias=ACTION_BIAS)
    ff = data["flow_field"]
    target_states = data["target_states"]
    norm = data["norm"]
    n_obj = norm.get("n_obj_total", 6)
    f_nf = float(norm["force_norm_fact"])
    s_dev = np.array(norm["sens_deviation"], dtype=np.float32)
    s_nf = np.array(norm["sens_norm_fact"], dtype=np.float32)

    save_target(args.out, target_states)
    save_norm(args.out, norm)

    model = load_model("vortex_lamb")
    log("Model loaded on CPU")

    # Restore + bias FIFO, then add vortex for pinball phase
    ff.restore_ddf(); ff.apply_ddf()

    bias_arr = np.zeros(n_obj, dtype=DATA_TYPE)
    bias_arr[3] = float(ACTION_BIAS[0] * U0)
    bias_arr[4] = float(ACTION_BIAS[1] * U0)
    bias_arr[5] = float(ACTION_BIAS[2] * U0)

    fifo = deque(maxlen=FIFO_LEN)
    for _ in range(FIFO_LEN):
        ff.run(SAMPLE_INTERVAL, bias_arr)
        fifo.append(ff.obs.copy()[0:12])

    # Add vortex at pinball phase position
    ff.add_vortex((15.0 * 20.0, (ff.FIELD_SHAPE[1] - 1) / 2.0, 0.0),
                   2.0 * 20.0, 0.5 * U0, 0.0, "lamb")

    # DRL inference
    sig_s = np.zeros((NUM_STEPS, 6), dtype=np.float32)
    sig_f = np.zeros((NUM_STEPS, 6), dtype=np.float32)
    sig_a = np.zeros((NUM_STEPS, 3), dtype=np.float32)

    raw = ff.obs.copy()[0:12]
    forces_norm = raw[6:12] / f_nf
    sens_norm = (raw[0:6] - s_dev) / s_nf
    obs = np.clip(np.hstack([forces_norm, sens_norm]), -1.0, 1.0).astype(np.float32)

    for step in range(NUM_STEPS):
        action, _ = model.predict(obs, deterministic=True)
        action = action.astype(np.float32).flatten()
        sig_a[step] = action.copy()

        action_arr = np.zeros(n_obj, dtype=DATA_TYPE)
        action_arr[3:] = (action * ACTION_SCALE + np.array(ACTION_BIAS, dtype=np.float32)) * U0

        ff.context.push()
        try:
            ff.run(SAMPLE_INTERVAL, action_arr)
        finally:
            ff.context.pop()

        raw = ff.obs.copy()[0:12]
        fifo.append(raw)
        sig_s[step] = raw[0:6]
        sig_f[step] = raw[6:12]

        forces_norm = raw[6:12] / f_nf
        sens_norm = (raw[0:6] - s_dev) / s_nf
        obs = np.clip(np.hstack([forces_norm, sens_norm]), -1.0, 1.0).astype(np.float32)

    save_signals(args.out, sig_s, sig_f, sig_a)
    np.savez_compressed(os.path.join(args.out, "controlled.npz"),
                        sensors=sig_s, forces=sig_f, actions=sig_a,
                        rewards=np.zeros(NUM_STEPS, dtype=np.float32))

    log("Comparing against reference...")
    result = compare_scene(REF_DIR, sig_s, sig_f, sig_a, conv_len=CONV_LEN, label="vortex_lamb")
    with open(os.path.join(args.out, "result.json"), "w") as f:
        json.dump(result, f, indent=2)

    log(f"PASS" if result["passed"] else "FAIL")
    del ff
    return 0 if result["passed"] else 1


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