import pytest
from target_simulator.core.models import Target, Waypoint, ManeuverType
from target_simulator.core import command_builder


@pytest.fixture
def sample_target() -> Target:
    """Provides a standard Target instance for testing command builders."""
    trajectory = [
        Waypoint(
            maneuver_type=ManeuverType.FLY_TO_POINT,
            target_range_nm=50.55,
            target_azimuth_deg=-25.11,
            target_altitude_ft=25000.0,
            target_velocity_fps=800.0,
            target_heading_deg=270.0,
        )
    ]
    # Creating a target automatically calls reset_simulation() which sets initial state
    target = Target(
        target_id=5,
        trajectory=trajectory,
        active=True,
        traceable=False,  # Test a non-traceable target
    )
    return target


def test_build_tgtinit(sample_target):
    """Tests the tgtinit command string generation."""
    command = command_builder.build_tgtinit(sample_target)

    # Usa i valori effettivi calcolati dal modello
    expected = (
        f"tgtinit {sample_target.target_id} "
        f"{sample_target.current_range_nm:.2f} "
        f"{sample_target.current_azimuth_deg:.2f} "
        f"{sample_target.current_velocity_fps:.2f} "
        f"{sample_target.current_heading_deg:.2f} "
        f"{sample_target.current_altitude_ft:.2f} "
        f"/s /-t"
    )
    assert command == expected


def test_build_tgtset_from_target_state(sample_target):
    """Tests the tgtset command string generation from a target's state."""
    # Let's simulate a small update to the target's state for the test
    sample_target.current_range_nm = 50.60
    sample_target.current_azimuth_deg = -25.20
    sample_target.current_velocity_fps = 805.5
    sample_target.current_heading_deg = 271.1
    sample_target.current_altitude_ft = 25050.0

    command = command_builder.build_tgtset_from_target_state(sample_target)

    # Expected format: tgtset <id> <range> <az> <vel> <hdg> <alt>
    expected = "tgtset 5 50.60 -25.20 805.50 271.10 25050.00"

    assert command == expected


def test_build_simple_commands():
    """Tests builders for simple, parameter-less commands."""
    assert command_builder.build_pause() == "pause"
    assert command_builder.build_continue() == "continue"
    assert command_builder.build_aclatch() == "aclatch"
    assert command_builder.build_acunlatch() == "acunlatch"
    assert command_builder.build_tgtreset() == "tgtreset -1"
    assert command_builder.build_tgtreset(target_id=8) == "tgtreset 8"
