#!/usr/bin/env python3
"""
analyze_all_blanks.py
======================
For every path where (under the new strict per-path TX/RX rule) main_a
or main_b would be blank, shows:
  - all PA.dat records where call_sign = <the blank site>  (its TX records)
  - all PA.dat records where receive_call_sign = <the other site> (records
    where the OTHER site is the receiver)

This is the same analysis done manually for WQVT999/WQVT998, run across
every blank case, to see if there's a consistent pattern (e.g. "the
blank site has a TX record toward a DIFFERENT site" vs "no TX records
at all").

Usage:
    python analyze_all_blanks.py ATT_Network.csv
"""
import argparse
import csv
import sys

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

ap = argparse.ArgumentParser()
ap.add_argument("network_csv", nargs="?", default="ATT_Network.csv")
ap.add_argument("--out", default="blank_antenna_analysis.csv")
ap.add_argument("--fcc-antennas", default="fcc_antennas.csv")
ap.add_argument("--fcc-paths", default="fcc_paths.csv")
args = ap.parse_args()

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

antennas = load_antennas(args.fcc_antennas)
path_records = load_path_records(args.fcc_paths)

# Build a full index: call_sign -> list of (receive_call_sign, path_number, ...)
# for ALL pairs (not just the pair in question) so we can see every TX
# record for the blank site, even toward a different site.
all_tx_by_cs = {}
all_rx_by_cs = {}
with open(args.fcc_paths, newline="") as f:
    for row in csv.DictReader(f):
        cs = row["call_sign"].strip()
        rx = row["receive_call_sign"].strip()
        all_tx_by_cs.setdefault(cs, []).append(row)
        all_rx_by_cs.setdefault(rx, []).append(row)

n_blank = 0
pattern_counts = {
    "tx_exists_toward_other": 0,       # has TX record toward the OTHER site (shouldn't happen if blank)
    "tx_exists_toward_different_site": 0,  # has TX record(s), but toward different site(s)
    "no_tx_records_at_all": 0,         # call sign has zero TX records in PA.dat
}

details = []

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)

    for site, other, missing in ((name_a, name_b, main_a is None), (name_b, name_a, main_b is None)):
        if not missing:
            continue
        n_blank += 1
        tx_records = all_tx_by_cs.get(site, [])
        targets = [r["receive_call_sign"].strip() for r in tx_records]

        if other in targets:
            pattern_counts["tx_exists_toward_other"] += 1
            cat = "tx_exists_toward_other"
        elif tx_records:
            pattern_counts["tx_exists_toward_different_site"] += 1
            cat = "tx_exists_toward_different_site"
        else:
            pattern_counts["no_tx_records_at_all"] += 1
            cat = "no_tx_records_at_all"

        details.append((path_id, site, other, cat, targets))

print(f"Total blank main-antenna instances: {n_blank}")
print()
for cat, count in pattern_counts.items():
    print(f"{cat}: {count}")
print()

with open(args.out, "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["path_id", "blank_site", "other_site", "category", "blank_site_tx_targets"])
    for path_id, site, other, cat, targets in details:
        w.writerow([path_id, site, other, cat, ";".join(targets)])

print(f"Wrote {len(details)} row(s) to {args.out}")
