from pathlib import Path
import struct
import sys


PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from autopilot_bridge import (
    AutopilotCommand,
    build_proto_udp_payload,
    select_proto_udp_target_state,
)


def test_select_proto_udp_target_state_uses_tracker_state_when_detection_is_lost():
    assert select_proto_udp_target_state(confirmed=False, miss_streak=0) == 0
    assert select_proto_udp_target_state(confirmed=True, miss_streak=0) == 1
    assert select_proto_udp_target_state(confirmed=True, miss_streak=4) == 3


def test_build_proto_udp_payload_encodes_offsets_and_bbox_area():
    cmd = AutopilotCommand()
    cmd.target_id = 7
    cmd.target_state = 1
    cmd.frame_w = 1000
    cmd.frame_h = 500
    cmd.aim_x = 650.0
    cmd.aim_y = 150.0
    cmd.bbox_w = 200.0
    cmd.bbox_h = 50.0

    payload = build_proto_udp_payload(cmd)
    unpacked = struct.unpack("<BBBhhbbB", payload)

    assert unpacked == (
        1,    # descriptor
        7,    # object_id
        1,    # target_state
        100,  # vertical px: up is positive
        150,  # horizontal px: right is positive
        40,   # vertical percent relative to half frame height
        30,   # horizontal percent relative to half frame width
        2,    # bbox area percent
    )


def test_build_proto_udp_payload_returns_zeroed_target_fields_when_target_is_missing():
    cmd = AutopilotCommand()
    cmd.target_id = None
    cmd.target_state = 0
    cmd.frame_w = 1280
    cmd.frame_h = 720
    cmd.aim_x = None
    cmd.aim_y = None
    cmd.bbox_w = None
    cmd.bbox_h = None

    payload = build_proto_udp_payload(cmd)
    unpacked = struct.unpack("<BBBhhbbB", payload)

    assert unpacked == (1, 0, 0, 0, 0, 0, 0, 0)
