"""Collect target cylinder baseline data (2D cylinder wake, Re=100).

Records the periodic vortex shedding from a single cylinder of specified diameter,
positioned at x=20*L0, with 3 sensors at x=30*L0.

Usage:
    conda run -n pycuda_3_10 python scripts/collect_target_cylinder.py --diameter 1.0 --device 2

Output: data/target_cylinder/target_cylinder_{diam}L/
"""
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

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

DATA_TYPE = np.float32


def collect():
    ap = argparse.ArgumentParser()
    ap.add_argument("--diameter", type=float, default=1.0,
                    help="Target cylinder diameter in L0 units (0.75, 1.0, 1.5)")
    ap.add_argument("--device", type=int, default=2)
    ap.add_argument("--steps", type=int, default=500)
    args = ap.parse_args()

    scene_name = f"target_cylinder_{args.diameter}L"
    if scene_name not in get_scene_list("target_cylinder"):
        print(f"Unknown scene: {scene_name}. Available: {get_scene_list('target_cylinder')}", flush=True)
        return

    cfg = get_scene(scene_name)
    out_dir = data_dir_for_scene(scene_name)
    u0 = cfg["u0"]
    si = cfg["sample_interval"]
    diam = args.diameter
    radius = diam * L0
    cyl_x = cfg["cylinder_x"]
    sensor_x = cfg["sensor_x"]
    print(f"Target cylinder: diameter={diam}L (radius={radius}), u0={u0}, si={si}", flush=True)
    print(f"Output: {out_dir}", flush=True)

    cuda_cfg, field_cfg = load_legacy_configs(LEGACY_CFG_DIR)
    field_cfg = field_cfg._replace(viscosity=float(cfg["nu"]), velocity=float(u0))

    ff = FlowField(field_cfg, cuda_cfg, device_id=args.device)

    # Add cylinder with specified diameter
    ff.add_cylinder((cyl_x * L0, CENTER_Y, 0.0), radius)
    # Add 3 sensors at x=sensor_x*L0
    for y_off in [2.0, 0.0, -2.0]:
        ff.add_sensor((sensor_x * L0, CENTER_Y + y_off * L0, 0.0), L0 / 4.0)

    n_obj = 4
    stabilize = int(4 * 1280 / u0)
    print(f"Stabilising target cylinder ({stabilize} steps)...", flush=True)
    ff.run(stabilize, np.zeros(n_obj, dtype=DATA_TYPE))
    print("Stabilisation done.", flush=True)

    # Record
    sens_list, forc_list = [], []
    ux_list, uy_list = [], []

    for step in range(args.steps):
        ff.run(si, np.zeros(n_obj, dtype=DATA_TYPE))
        obs = ff.obs.copy()
        sens_list.append(obs[2:8])   # 3 sensors x 2 = 6
        forc_list.append(obs[0:2])   # cylinder force (fx, fy)
        ux, uy = get_velocity_field(ff, u0=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))

    omega = vorticity_from_ddf(ff, u0=u0)
    save_vorticity_png(os.path.join(out_dir, "vorticity.png"),
                       omega, title=f"Target cylinder {diam}L, u0={u0}")

    # Strouhal number
    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 * (diam * L0) / u0
    print(f"St={St:.4f} (f_dom={f_dom:.6f}, T={T_dom:.0f})", flush=True)

    meta = dict(cfg, St=St, f_dom=f_dom, n_steps=args.steps)
    with open(os.path.join(out_dir, "meta.json"), "w") as f:
        json.dump(meta, f, indent=2)

    del ff
    print(f"Done, saved to {out_dir}", flush=True)


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