# OID_analysis/scripts/collect_empty_channel.py
"""
Collect empty channel reference (q_in for steady cloak and illusion scenes).

Usage:
    conda run -n pycuda_3_10 python src/OID_analysis/scripts/collect_empty_channel.py \
        --device 3 --steps 200
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

import numpy as np

_REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
if _REPO not in sys.path:
    sys.path.insert(0, _REPO)
_SRC = os.path.join(_REPO, "src")
if _SRC not in sys.path:
    sys.path.insert(0, _SRC)

from LegacyCelerisLab import FlowField  # noqa: E402
from OID_analysis.utils.cfd_interface import (  # noqa: E402
    load_legacy_configs, get_velocity_field, save_vorticity_png, vorticity_from_ddf,
)
from OID_analysis.configs import get_scene, data_dir_for_scene, LEGACY_CFG_DIR  # noqa: E402

DATA_TYPE = np.float32
L0 = 20.0
CENTER_Y = (512 - 1) / 2.0
SAMPLE_INTERVAL = 800


def collect(device_id: int, n_steps: int) -> str:
    cfg = get_scene("empty_channel")
    u0 = cfg["u0"]
    out_dir = data_dir_for_scene("empty_channel")
    os.makedirs(out_dir, exist_ok=True)

    cuda_cfg, field_cfg = load_legacy_configs(LEGACY_CFG_DIR)

    ff = FlowField(field_cfg, cuda_cfg, device_id=device_id)
    print(f"  Empty channel: {ff.FIELD_SHAPE}")

    # Add 3 sensors (matching legacy cloak env layout)
    for y_off in [2.0, 0.0, -2.0]:
        ff.add_sensor((40.0 * L0, CENTER_Y + y_off * L0, 0.0), L0 / 4.0)

    # Stabilize
    n_stab = int(4 * ff.FIELD_SHAPE[0] / u0)
    print(f"  Stabilising {n_stab} steps ...")
    ff.run(n_stab, np.zeros(3, dtype=DATA_TYPE))

    # Record
    sens_list, ux_list, uy_list = [], [], []
    for step in range(n_steps):
        ff.run(SAMPLE_INTERVAL, np.zeros(3, dtype=DATA_TYPE))
        obs_slice = ff.obs.copy()[0:6]
        sens_list.append(obs_slice)
        ux, uy = get_velocity_field(ff, u0=u0)
        ux_list.append(ux)
        uy_list.append(uy)

    np.savez(os.path.join(out_dir, "sensors.npz"),
             sensors=np.array(sens_list, dtype=np.float32))
    np.savez_compressed(os.path.join(out_dir, "fields.npz"),
                        ux=np.stack(ux_list), uy=np.stack(uy_list))

    omega = vorticity_from_ddf(ff, u0=u0)
    save_vorticity_png(os.path.join(out_dir, "vorticity_empty_channel.png"),
                       omega, title="Empty channel")

    # Save config
    with open(os.path.join(out_dir, "config.json"), "w") as f:
        json.dump({k: str(v) if not isinstance(v, (int, float, list, bool)) else v
                   for k, v in cfg.items()}, f, indent=2)

    del ff
    print(f"  Saved {n_steps} snapshots to {out_dir}")
    return out_dir


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--device", type=int, default=3)
    ap.add_argument("--steps", type=int, default=200)
    args = ap.parse_args()

    t0 = time.time()
    out = collect(args.device, args.steps)
    print(f"Done in {time.time() - t0:.1f}s -> {out}")


if __name__ == "__main__":
    main()
