import math
from target_simulator.core.command_builder import build_tgtinit
from target_simulator.core.models import Waypoint, Target, NM_TO_FT

METERS_PER_NM = 1852.0


def test_build_tgtinit_contains_parameters():
    wp = Waypoint(
        maneuver_type=Waypoint.maneuver_type,  # placeholder, not used by builder
        target_range_nm=30.0,
        target_azimuth_deg=10.0,
        target_altitude_ft=10000.0,
        target_velocity_fps=506.34,
        target_heading_deg=25.0,
    )
    t = Target(target_id=0, trajectory=[wp])
    # Make sure flags are set as expected
    t.active = True
    t.traceable = True
    t.restart = True
    # Set current kinematics to match waypoint (build_tgtinit reads current_* fields)
    t.current_range_nm = 30.0
    t.current_azimuth_deg = 10.0
    t.current_heading_deg = 25.0
    t.current_altitude_ft = 10000.0
    t.current_velocity_fps = 506.34

    cmd = build_tgtinit(t)
    # command should start with tgtinit and contain the numeric fields in order
    parts = cmd.split()
    assert parts[0] == "tgtinit"
    assert parts[1] == "0"
    assert parts[2] == "30.00"
    assert parts[3] == "10.00"
    # velocity is formatted as fps
    assert parts[4] == "506.34"
    assert parts[5] == "25.00"
    assert parts[6] == "10000.00"
    # qualifiers should contain /s /t /r (order may vary for /r appended)
    qualifiers = parts[7:]
    assert "/s" in qualifiers
    assert "/t" in qualifiers
    assert "/r" in qualifiers


def test_command_to_ris_coordinate_roundtrip():
    """Simula il percorso: command params -> RIS coords (meters) -> GUI azimuth -> reconstruct coords.
    Verifica che la ricostruzione torni alle stesse coordinate (round-trip) entro tolleranza.
    """
    range_nm = 40.0
    az_deg = 20.0
    alt_ft = 10000.0

    # Simulate server: produce RIS X,Y in meters using conventional conversion
    rad = math.radians(az_deg)
    x_m = range_nm * METERS_PER_NM * math.sin(rad)
    y_m = range_nm * METERS_PER_NM * math.cos(rad)

    # GUI receives x_m,y_m and computes az_gui = degrees(atan2(y,x)).
    # Given server uses x = R*sin(az) and y = R*cos(az),
    # az_gui should equal (90° - az) modulo 360.
    az_gui = math.degrees(math.atan2(y_m, x_m)) % 360
    expected = (90.0 - az_deg) % 360
    assert math.isclose(az_gui, expected, rel_tol=1e-9, abs_tol=1e-6)
