#!/usr/bin/env python3
"""
check_tx_rx.py
===============
For every path with a blank main antenna on one side, checks whether
that site was the TRANSMIT or RECEIVE side of the relevant PA.dat
record(s), to see if blanks correlate with one role.

Usage:
    python check_tx_rx.py ATT_Network.csv
"""
import csv
import sys

sys.path.insert(0, ".")
from populate_summary_v2 import load_antennas, load_path_records, find_main_div

net_csv = sys.argv[1] if len(sys.argv) > 1 else "ATT_Network.csv"

with open(net_csv, newline="") as f:
    rows = [r for r in csv.DictReader(f) if r.get("Ref_ID", "").strip().isdigit()]

antennas = load_antennas("fcc_antennas.csv")
path_records = load_path_records("fcc_paths.csv")

tx_blank = 0
rx_blank = 0
neither_role = 0  # site never appears as tx or rx in any PA record for this pair
total_blank_sides = 0

examples_tx = []
examples_rx = []

for row in rows:
    name_a, name_b = row["Site_A_Call_Sign"], row["Site_B_Call_Sign"]
    path_id = row["Path_ID2"]
    main_a, div_a, main_b, div_b = find_main_div(name_a, name_b, antennas, path_records)

    records = path_records.get(frozenset((name_a, name_b)), [])

    for site, missing in ((name_a, main_a is None), (name_b, main_b is None)):
        if not missing:
            continue
        total_blank_sides += 1
        # was `site` the tx or rx call_sign in any PA record for this pair?
        roles = set()
        for r in records:
            if r["call_sign"].strip() == site:
                roles.add("tx")
            if r["receive_call_sign"].strip() == site:
                roles.add("rx")
        if "tx" in roles and "rx" not in roles:
            tx_blank += 1
            if len(examples_tx) < 5:
                examples_tx.append((path_id, site))
        elif "rx" in roles and "tx" not in roles:
            rx_blank += 1
            if len(examples_rx) < 5:
                examples_rx.append((path_id, site))
        elif "tx" in roles and "rx" in roles:
            # appears as both across different PA records -- check which
            # specific reference is missing
            tx_blank += 1  # count separately below if needed
        else:
            neither_role += 1

print(f"Total blank main-antenna site-instances: {total_blank_sides}")
print(f"  Site was TX-only in PA.dat (but antenna record missing): {tx_blank}")
print(f"  Site was RX-only in PA.dat (but antenna record missing): {rx_blank}")
print(f"  Site never appears in any PA record for this pair:       {neither_role}")
print()
print("TX-blank examples:", examples_tx)
print("RX-blank examples:", examples_rx)
