#!/usr/bin/env python3
"""
check_azimuth_for_blank.py
============================
For a given call sign (the "blank site") and the coordinates of its
path partner, dumps ALL of the blank site's AN.dat antenna records
(height, azimuth field, location_number) alongside that location's
LO.dat coordinates, and computes the bearing from each location toward
the partner's coordinates -- to see if azimuth+location can identify
which antenna serves this path.

Usage:
    python check_azimuth_for_blank.py WQVT999 42.xx -116.xx
    (lat/lon = the OTHER site's coordinates, from ATT_Network.csv)
"""
import io
import sys
import zipfile

import pyproj

CS = sys.argv[1]
OTHER_LAT = float(sys.argv[2])
OTHER_LON = float(sys.argv[3])

geod = pyproj.Geod(ellps="WGS84")


def dms_to_decimal(deg, minutes, sec, direction):
    try:
        d, m, s = float(deg), float(minutes), float(sec)
    except ValueError:
        return None
    val = d + m / 60.0 + s / 3600.0
    if direction.strip().upper() in ("S", "W"):
        val = -val
    return val


with zipfile.ZipFile("l_micro.zip") as z:
    # --- LO.dat: get lat/lon for each location_number of this call sign
    locations = {}
    with z.open("LO.dat") as raw:
        for line in io.TextIOWrapper(raw, encoding="latin-1"):
            fields = line.rstrip("\n").split("|")
            cs = fields[4].strip() if len(fields) > 4 else ""
            if cs != CS:
                continue
            loc = fields[8].strip() if len(fields) > 8 else ""
            lat = dms_to_decimal(fields[19], fields[20], fields[21], fields[22])
            lon = dms_to_decimal(fields[23], fields[24], fields[25], fields[26])
            locations[loc] = (lat, lon)
            print(f"LO.dat: {CS} location={loc} lat={lat} lon={lon}")

    print()

    # --- AN.dat: every antenna record for this call sign, all fields
    print(f"AN.dat records for {CS}:")
    with z.open("AN.dat") as raw:
        for line in io.TextIOWrapper(raw, encoding="latin-1"):
            fields = line.rstrip("\n").split("|")
            cs = fields[4].strip() if len(fields) > 4 else ""
            if cs != CS:
                continue
            loc = fields[7].strip() if len(fields) > 7 else ""
            ant = fields[6].strip() if len(fields) > 6 else ""
            height = fields[11].strip() if len(fields) > 11 else ""
            nonblank = {idx: v for idx, v in enumerate(fields, 1) if v.strip()}
            print(f"  location={loc} antenna={ant} height={height}")
            print(f"    all fields: {nonblank}")

            site_latlon = locations.get(loc)
            if site_latlon and site_latlon[0] is not None:
                az_to_other, _, _ = geod.inv(site_latlon[1], site_latlon[0], OTHER_LON, OTHER_LAT)
                az_to_other %= 360
                print(f"    location {loc} coords={site_latlon}, bearing to other site = {az_to_other:.2f} deg")
