"""coordinates.py - observation time and location extraction for LVM data processing."""

# NOTE: Code is generated by an LLM and may not be fully robust.

import astropy.units as u
from astropy.coordinates import EarthLocation
from astropy.io.fits import Header
from astropy.time import Time


def get_mjd(header: Header) -> float:
    # Method 1: Use INTSTART and INTEND if available (most precise)
    if "INTSTART" in header and "INTEND" in header:
        start_time = Time(header["INTSTART"], format="isot")
        end_time = Time(header["INTEND"], format="isot")
        mid_time = start_time + (end_time - start_time) / 2
        # print(header["MJD"])
        # mid_time = Time(header["MJD"], format="mjd")
        # print(mid_time.mjd)
        # print()

        # Validation: check against header EXPTIME
        # calculated_exptime = (end_time - start_time).to(u.second).value
        # header_exptime = header.get("EXPTIME", 0.0)
        # if abs(calculated_exptime - header_exptime) > 1.0:  # Allow 1s tolerance
        #     print(
        #         f"  WARNING: Calculated exptime ({calculated_exptime:.1f}s) differs from header EXPTIME ({header_exptime}s)"
        #     )

        return mid_time.mjd

    # # Method 2: Use OBSTIME + EXPTIME/2 as fallback
    # elif "OBSTIME" in header and "EXPTIME" in header:
    #     start_time = Time(header["OBSTIME"], format="isot")
    #     exptime = header["EXPTIME"] * u.second
    #     mid_time = start_time + exptime / 2

    #     return mid_time.mjd

    # # Method 3: Use header MJD + EXPTIME/2 (least precise, integer MJD)
    # elif "MJD" in header and "EXPTIME" in header:
    #     mjd_start = header["MJD"]  # This appears to be integer MJD
    #     exptime_days = header["EXPTIME"] / 86400.0  # Convert seconds to days
    #     mjd_mid = mjd_start + exptime_days / 2

    #     return mjd_mid

    else:
        raise ValueError("Could not find sufficient time information in header")


def get_observatory_code(header: Header) -> str:
    observatory = header.get("OBSERVAT", "").strip()

    # Just return the observatory code string
    # You can convert to EarthLocation later when needed
    known_observatories = ["LCO"]  # Add other LVM observatory codes as needed

    if observatory in known_observatories:
        return observatory
    else:
        raise ValueError(
            f"Unknown observatory: {observatory}. Known observatories: {known_observatories}"
        )


def get_observatory_location(observatory: str) -> EarthLocation:
    # LCO = Las Campanas Observatory
    if observatory == "LCO":
        return EarthLocation.of_site("Las Campanas Observatory")
    else:
        # Add other observatories as needed
        raise ValueError(f"Unknown observatory: {observatory}")
