Source code for arlmet._header

"""Binary codec for the fixed 50-byte ARL record header."""

import string
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, ClassVar

import pandas as pd

from arlmet._exceptions import ARLFormatError
from arlmet._grid import Grid
from arlmet._time import ensure_timestamp

__all__ = ["Header"]

# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------


def restore_year(yr: str | int) -> int:
    """
    Convert 2-digit year to 4-digit year.

    Years < 40 are mapped to 2000+yr, otherwise 1900+yr.
    Already 4-digit years (>= 1900) are returned unchanged.
    """
    yr = int(yr)
    if yr >= 1900:
        return yr
    return 2000 + yr if (yr < 40) else 1900 + yr


FIRST_YEAR = 1940
LAST_YEAR = 2039


def check_year(year: int) -> int:
    """Return *year*, or raise if the two-digit year of an ARL label cannot hold it."""
    if not FIRST_YEAR <= year <= LAST_YEAR:
        raise ValueError(
            f"ARL files hold a two-digit year, so times must be from {FIRST_YEAR} "
            f"to {LAST_YEAR}; got the year {year}."
        )
    return year


def check_level_count(n_levels: int) -> None:
    """
    Raise if *n_levels* levels above the surface do not fit an ARL file.

    A record's header numbers its level in two characters, so a file holds
    the surface and at most :attr:`Header.MAX_LEVEL` levels above it.
    """
    if n_levels > Header.MAX_LEVEL:
        raise ValueError(
            f"An ARL file holds at most {Header.MAX_LEVEL} levels above the "
            f"surface (a record's header numbers its level in two characters); "
            f"got {n_levels}."
        )


def letter_to_thousands(char: str) -> int:
    """Convert a header grid character to thousands: A=1000, B=2000, …; else 0."""
    if char in string.ascii_uppercase:
        return (string.ascii_uppercase.index(char) + 1) * 1000
    return 0


def thousands_to_letter(value: int) -> str:
    """
    Convert a thousands value to its ARL grid header character.

    As HYSPLIT's ``pakset`` writes it, ``CHAR(64 + thousands)``: ``@`` for
    none, ``A`` for 1000, ``B`` for 2000, and so on. HYSPLIT's ``metset``
    reads both characters so once either is ``@`` or above, so a grid with
    one axis of 1000 or more needs ``@`` on the other (``9`` there reads as
    -7000). A grid under 1000 on both axes has the grid number ``99`` instead
    (:meth:`Header.tobytes`).
    """
    if value % 1000 != 0 or value < 0 or value > 26000:
        raise ValueError(f"Unsupported grid thousands value: {value}")
    return chr(64 + value // 1000)


def format_fortran_float(value: float) -> str:
    """
    Format a float as Fortran's ``E14.7`` writes it, as HYSPLIT's ``pakrec`` does.

    Seven significant digits, rounded from the exact binary value with ties
    to even (``f"{value:.6e}"`` rounds that way), as ``0.dddddddE+xx``.
    """
    if value == 0.0:
        return " 0.0000000E+00"
    mantissa, exponent = f"{value:.6e}".split("e")
    sign = "-" if value < 0 else " "
    digits = mantissa.lstrip("-").replace(".", "")
    return f"{sign}0.{digits}E{int(exponent) + 1:+03d}"


def format_fixed_width_float(value: float, width: int) -> str:
    """
    Format a float into a fixed-width decimal field for index records.

    The field always holds a decimal point (``11000.``, as HYSPLIT's own
    ``F6.0`` writes it): HYSPLIT reads level heights with ``F6.2``, which takes
    a field without one as having two implied decimals (``" 11000"`` is
    110.00). A value too large to fit with a point raises ``ValueError``.
    """
    if width < 2:
        raise ValueError("width must be at least 2")

    if value == 0.0:
        return "." + ("0" * (width - 1))

    for decimals in range(width, -1, -1):
        text = f"{value:.{decimals}f}" + ("." if decimals == 0 else "")
        if text.startswith("0.") and len(text) - 1 <= width:
            text = text[1:]
        elif text.startswith("-0.") and len(text) - 1 <= width:
            text = "-" + text[2:]

        if len(text) <= width:
            return text.rjust(width)

    raise ValueError(f"Value {value} cannot be represented in width {width}")


def split_grid_component(total: int) -> tuple[int, int]:
    """Split a total grid dimension into thousands and remainder components."""
    if total < 0:
        raise ValueError("Grid dimensions must be non-negative.")
    return (total // 1000) * 1000, total % 1000


def record_length_from_grid(grid: Grid) -> int:
    """
    Calculate the ARL record length for a given grid.

    Record length is the fixed header length plus the number of grid points.
    """
    return Header.N_BYTES + grid.nx * grid.ny


# ---------------------------------------------------------------------------
# Header
# ---------------------------------------------------------------------------