"""Standalone smoke test for Compact-M K209 VISA HiSLIP acquisition."""

from __future__ import annotations

import argparse

import numpy as np

from python_app.hardware_full.compact_m_k209_service import CompactMK209Service
from python_app.models.run_config_model import RadarSweepModel


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Acquire one K209 sweep through VISA HiSLIP")
    parser.add_argument(
        "--resource",
        required=True,
        help=(
            "S2VNA VISA resource, e.g. TCPIP0::127.0.0.1::hislip0,4880::INSTR "
            "when the USB-connected K209 is controlled by local S2VNA"
        ),
    )
    parser.add_argument("--start-hz", type=float, default=1_000_000.0)
    parser.add_argument("--stop-hz", type=float, default=6_000_000_000.0)
    parser.add_argument("--points", type=int, default=201)
    parser.add_argument("--ifbw-hz", type=float, default=50_000.0)
    parser.add_argument("--power-dbm", type=float, default=-10.0)
    parser.add_argument("--timeout-ms", type=int, default=20_000)
    parser.add_argument("--no-preset", action="store_true")
    parser.add_argument(
        "--visa-library",
        default="@ivi",
        help="PyVISA IVI backend specification, e.g. @ivi or /usr/lib/x86_64-linux-gnu/libvisa.so",
    )
    return parser.parse_args()


def _validate_result(result, expected_points: int) -> None:
    if result.x.shape != (expected_points,):
        raise RuntimeError(f"Unexpected frequency shape: {result.x.shape}")
    s11 = result.trace("s11")
    s21 = result.trace("s21")
    if s11.shape != (expected_points,) or s21.shape != (expected_points,):
        raise RuntimeError(f"Unexpected trace shapes: s11={s11.shape}, s21={s21.shape}")
    if not np.all(np.isfinite(result.x)):
        raise RuntimeError("Frequency axis contains non-finite values")
    if np.any(np.diff(result.x) < 0.0):
        raise RuntimeError("Frequency axis is not monotonic")
    if not np.all(np.isfinite(s11.real)) or not np.all(np.isfinite(s11.imag)):
        raise RuntimeError("S11 contains non-finite values")
    if not np.all(np.isfinite(s21.real)) or not np.all(np.isfinite(s21.imag)):
        raise RuntimeError("S21 contains non-finite values")


def main() -> int:
    args = _parse_args()
    sweep = RadarSweepModel(
        start_hz=args.start_hz,
        stop_hz=args.stop_hz,
        points=args.points,
        if_bandwidth_hz=args.ifbw_hz,
        power_dbm=args.power_dbm,
    )

    service = CompactMK209Service(
        resource=args.resource,
        timeout_ms=args.timeout_ms,
        preset_on_open=not args.no_preset,
        visa_library=args.visa_library,
    )
    try:
        service.open()
        print(f"K209 IDN: {service.query_identity()}")
        service.configure(sweep)
        result = service.acquire()
        _validate_result(result, args.points)
        system_error = service.query_system_error()
        if not system_error.startswith("0,"):
            raise RuntimeError(f"K209 SCPI error after sweep: {system_error}")
        print(
            "K209 sweep OK: "
            f"points={result.x.size}, first_hz={result.x[0]:.3f}, last_hz={result.x[-1]:.3f}, "
            f"mean_abs_s11={np.mean(np.abs(result.trace('s11'))):.6g}, "
            f"mean_abs_s21={np.mean(np.abs(result.trace('s21'))):.6g}"
        )
    finally:
        service.close()
    return 0


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