"""
FSWidget simulator feed for SkyBridge using shared Abflug SimulatorDataSource.

Does not use UDP or the vendored map/rewinger stack. Attitude (pitch/roll) is
not available from FSWidget; AircraftStateManager falls back to GPS track.
"""

from __future__ import annotations

import os
import sys
import time
from types import SimpleNamespace
from typing import Any, Dict, Optional

# clients_v3_1 root (parent of skybridge package)
_CLIENT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if _CLIENT_ROOT not in sys.path:
    sys.path.insert(0, _CLIENT_ROOT)

from simulator_data_source import DataSourceType, SimulatorDataSource  # noqa: E402

RECEIVE_TIMEOUT = 5.0


class SimulatorTelemetrySource:
    """Poll FSWidget TCP via SimulatorDataSource; exposes get_latest_data() for RadioDisplay."""

    def __init__(self, fswidget_ip: str = "localhost"):
        self.fswidget_ip = (fswidget_ip or "localhost").strip() or "localhost"
        self._source: Optional[SimulatorDataSource] = None

    def set_host(self, host: str) -> None:
        self.fswidget_ip = (host or "localhost").strip() or "localhost"

    def start(self) -> None:
        self.stop()
        self._source = SimulatorDataSource(
            source_type=DataSourceType.FSWIDGET,
            fswidget_ip=self.fswidget_ip,
            auto_detect=False,
        )
        self._source.start()

    def stop(self) -> None:
        if self._source is not None:
            self._source.stop()
            self._source = None

    def restart(self) -> None:
        self.start()

    def get_latest_data(self) -> Dict[str, Any]:
        if self._source is None:
            return {"gps": None, "attitude": None, "aircraft": None, "traffic": {}, "connected": False}

        raw = self._source.latest_gps
        connected = (time.time() - self._source.last_gps_time) < RECEIVE_TIMEOUT

        if raw is None:
            return {
                "gps": None,
                "attitude": None,
                "aircraft": None,
                "traffic": {},
                "connected": connected,
            }

        gps = SimpleNamespace(
            latitude=raw.latitude,
            longitude=raw.longitude,
            altitude=raw.altitude,
            track=raw.track,
            ground_speed=raw.ground_speed,
            indicated_air_speed=raw.indicated_air_speed,
        )
        return {
            "gps": gps,
            "attitude": None,
            "aircraft": None,
            "traffic": {},
            "connected": connected,
        }
