"""Collect pinball baseline data.

Usage:
    conda run -n pycuda_3_10 python scripts/collect_pinball.py --device 2

Output: data/pinball/pinball/
"""
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)
_ANALYSIS = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if _ANALYSIS not in sys.path:
    sys.path.insert(0, _ANALYSIS)

from LegacyCelerisLab import FlowField

from CCD_analysis.configs import get_scene, data_dir_for_scene, LEGACY_CFG_DIR
from CCD_analysis.utils.cfd_interface import (
    load_legacy_configs, get_velocity_field, save_vorticity_png,
)


def collect():
    ap = argparse.ArgumentParser()
    ap.add_argument("--device", type=int, default=2)
    args = ap.parse_args()

    cfg = get_scene("pinball")
    out_dir = data_dir_for_scene("pinball")
    cuda_cfg, field_cfg = load_legacy_configs(LEGACY_CFG_DIR)
    field_cfg = field_cfg._replace(viscosity=float(cfg["nu"]))

    ff = FlowField(field_cfg, cuda_cfg, device_id=args.device)
    for sc_y in [40.0, 40.0, 40.0]:
        pass  # sensor positions handled below
    from CCD_analysis.configs import L0, CENTER_Y
    l0 = L0
    # sensors
    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)
    # pinball
    ff.add_cylinder((30.0 * l0, CENTER_Y, 0.0), l0 / 2.0)
    ff.add_cylinder((31.3 * l0, CENTER_Y + 0.75 * l0, 0.0), l0 / 2.0)
    ff.add_cylinder((31.3 * l0, CENTER_Y - 0.75 * l0, 0.0), l0 / 2.0)

    n_obj = 6
    stabilize = int(4 * 1280 / cfg["u0"])
    print(f"Stabilising ({stabilize} steps)...")
    ff.run(stabilize, np.zeros(n_obj, dtype=np.float32))

    n_steps = 200
    si = cfg["sample_interval"]
    sens_list, forc_list = [], []
    ux_list, uy_list = [], []

    for step in range(n_steps):
        ff.run(si, np.zeros(n_obj, dtype=np.float32))
        obs = ff.obs.copy()
        sens_list.append(obs[0:6])
        forc_list.append(obs[6:12])
        ux, uy = get_velocity_field(ff, u0=cfg["u0"])
        ux_list.append(ux)
        uy_list.append(uy)

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

    # Vorticity
    from CCD_analysis.utils.cfd_interface import vorticity_from_ddf
    omega = vorticity_from_ddf(ff, u0=cfg["u0"])
    save_vorticity_png(os.path.join(out_dir, "vorticity.png"),
                       omega, title="Pinball uncontrolled Re=100")

    # Meta
    from CCD_analysis.utils.resampling import detect_dominant_frequency
    signal = np.array(sens_list, dtype=np.float32)[:, 3]
    f_dom, T_dom, _ = detect_dominant_frequency(signal, float(si))
    St = f_dom * 20.0 / cfg["u0"]
    meta = dict(cfg, St=St, f_dom=f_dom, n_steps=n_steps)
    with open(os.path.join(out_dir, "meta.json"), "w") as f:
        json.dump(meta, f, indent=2)
    print(f"St={St:.4f}, done")

    del ff


if __name__ == "__main__":
    t0 = time.time()
    collect()
    print(f"Time: {time.time() - t0:.1f}s")
