# target_simulator/core/command_builder.py

"""
Constructs MMI command strings based on high-level data models.
"""

from typing import Dict, Any

from .models import Target
from target_simulator.utils.logger import get_logger

logger = get_logger(__name__)


def build_tgtinit(target: Target) -> str:
    """
    Builds the 'tgtinit' command from a target's initial state.
    After the refactor, the target object's state is pre-calculated
    by reset_simulation(), so we can read kinematics directly.
    """
    params = [
        target.target_id,
        f"{target.current_range_nm:.2f}",
        f"{target.current_azimuth_deg:.2f}",
        f"{target.current_velocity_fps:.2f}",
        f"{target.current_heading_deg:.2f}",
        f"{target.current_altitude_ft:.2f}",
    ]
    qualifiers = ["/s" if target.active else "/-s", "/t" if target.traceable else "/-t"]
    if hasattr(target, "restart") and getattr(target, "restart", False):
        qualifiers.append("/r")

    command_parts = ["tgtinit"] + [str(p) for p in params] + qualifiers
    full_command = " ".join(command_parts)

    logger.debug(f"Built command: {full_command!r}")
    return full_command


def build_tgtset_from_target_state(target: Target) -> str:
    """
    Builds the 'tgtset' command from a target's CURRENT dynamic state.
    This is used for continuous updates during simulation.
    """
    # Note: We do not include qualifiers like /s or /t in continuous updates
    # as they are typically set only at initialization.
    params = [
        target.target_id,
        f"{target.current_range_nm:.2f}",
        f"{target.current_azimuth_deg:.2f}",
        f"{target.current_velocity_fps:.2f}",
        f"{target.current_heading_deg:.2f}",
        f"{target.current_altitude_ft:.2f}",
    ]

    command_parts = ["tgtset"] + [str(p) for p in params]
    full_command = " ".join(command_parts)

    # We lower the log level to SPAM/VERBOSE if available, or DEBUG,
    # to avoid flooding the log during live simulation.
    logger.debug(f"Built state update command: {full_command!r}")
    return full_command


def build_tgtset_selective(target_id: int, updates: Dict[str, Any]) -> str:
    """
    Builds a 'tgtset' command with skippable parameters ('*').
    """
    param_order = [
        "range_nm",
        "azimuth_deg",
        "velocity_fps",
        "heading_deg",
        "altitude_ft",
    ]
    params = [str(updates.get(key, "*")) for key in param_order]
    command_parts = ["tgtset", str(target_id)] + params
    full_command = " ".join(command_parts)
    logger.debug(f"Built selective command: {full_command!r}")
    return full_command


# --- Simple Command Builders ---


def build_tgtreset(target_id: int = -1) -> str:
    """Builds the 'tgtreset' command. ID -1 resets all targets."""
    return f"tgtreset {target_id}"


def build_pause() -> str:
    """Builds the 'pause' command."""
    return "pause"


def build_continue() -> str:
    """Builds the 'continue' command."""
    return "continue"


def build_aclatch() -> str:
    """Builds the 'aclatch' command to latch A/C data."""
    return "aclatch"


def build_acunlatch() -> str:
    """Builds the command to release the A/C data latch."""
    return "acunlatch"
