# radar_data_reader/core/structures/tracking_structures.py

"""
Contains ctypes structure definitions and dataclass wrappers related to
Air-to-Air (A-A) target tracking data, typically found in DSPHDROUT,
STT (Single Target Track), and MTT (Multi Target Track) blocks.
"""

import ctypes
from dataclasses import dataclass
from typing import Optional

from .base_structures import (
    CtypesStructureBase,
    BaseBlock,
    c_boolean,
    c_radians_t,
    c_metres_t,
    c_metres_per_sec_t,
)

# ==================================================================================================
# --- Tracking Sub-Structures ---
# ==================================================================================================


class TargetFilteringResults(CtypesStructureBase):
    """Represents the state estimation for a single axis (e.g., Azimuth)."""

    _fields_ = [
        ("state_estimation", ctypes.c_float * 4),
        ("covariance_matrix", ctypes.c_float * 16),
        ("residual", ctypes.c_float),
        ("normalized_residual", ctypes.c_float),
        ("residual_variance", ctypes.c_float),
        ("validity_of_the_measure", c_boolean),
        ("filter_is_working", c_boolean),
    ]


class MostImportantTargetData(CtypesStructureBase):
    """Contains all tracking information for the primary target."""

    _fields_ = [
        ("target_id", ctypes.c_int),
        ("target_is_valid", c_boolean),
        ("range_filtering_results", TargetFilteringResults),
        ("range_rate_filtering_results", TargetFilteringResults),
        ("azimuth_filtering_results", TargetFilteringResults),
        ("elevation_filtering_results", TargetFilteringResults),
    ]


class TrackManagementData(CtypesStructureBase):
    """Contains management and status data for the tracking process."""

    _fields_ = [
        ("track_is_on", c_boolean),
        ("track_file_is_valid", c_boolean),
        ("target_is_on_track", c_boolean),
        ("type_of_tracking", ctypes.c_int),
        ("time_on_track", ctypes.c_float),
        ("track_file_age", ctypes.c_float),
        ("number_of_consecutive_misses", ctypes.c_int),
        ("boresight_error_azimuth", c_radians_t),
        ("boresight_error_elevation", c_radians_t),
    ]


# ==================================================================================================
# --- Top-Level Tracking Structure (STT) ---
# ==================================================================================================


class LocalAATrackingData(CtypesStructureBase):
    """The main structure for Single Target Track (STT) data."""

    _fields_ = [
        ("data_for_the_most_important_target", MostImportantTargetData),
        ("track_management", TrackManagementData),
    ]


@dataclass
class SttBlock(BaseBlock):
    """Dataclass wrapper for a parsed STT (Single Target Track) block."""

    is_valid: bool
    tracking_data: Optional[LocalAATrackingData] = None