"""Offline JSON :class:`FlightDto` loader (AZ-489).

The ``--flight-file`` CLI flag in AZ-326 lands here when the operator
workstation has no path to the parent-suite ``flights`` REST service. The
file format is the same JSON shape the online endpoint returns (FAC-INV-1).
"""

from __future__ import annotations

from pathlib import Path

import orjson

from gps_denied_onboard.components.c12_operator_tooling.flights_api._parser import (
    parse_flight_payload,
)
from gps_denied_onboard.components.c12_operator_tooling.flights_api.errors import (
    FlightFileNotFoundError,
    FlightsApiSchemaError,
)
from gps_denied_onboard.components.c12_operator_tooling.flights_api.interface import (
    FlightDto,
)

__all__ = ["load_flight_file"]


def load_flight_file(*, path: Path) -> FlightDto:
    """Load a :class:`FlightDto` from a JSON file on disk.

    Raises:
        FlightFileNotFoundError: ``path`` does not exist.
        FlightsApiSchemaError: the file is not well-formed JSON OR the
            decoded payload violates the DTO shape.
        WaypointSchemaError: an individual waypoint inside the file is
            malformed.
    """
    if not path.exists():
        raise FlightFileNotFoundError(f"flight file {path!s} does not exist")
    raw = path.read_bytes()
    try:
        payload = orjson.loads(raw)
    except orjson.JSONDecodeError as exc:
        raise FlightsApiSchemaError(
            f"flight file {path!s}: not valid JSON: {exc}"
        ) from exc
    return parse_flight_payload(payload, source_label=f"flight file {path!s}")
