"""Coverage evaluation for the away-2020 benchmark scenes (self-contained).

Metric (identical to the paper): for every annotated 20 m fire-pixel center,
compute the great-circle distance to every retained detection point; a fire
pixel counts as covered if the nearest detection is within 750 m. The scene
score is the fraction of fire pixels covered.

Detections are read from the CSVs under ./detections/; rows are retained when
the `detected` column (if present) is True, i.e. the detector's own decision
threshold (objectness >= 0.5) was met.

Run:  python eval_coverage.py     (from this directory; needs numpy + rasterio)
"""
import csv
from pathlib import Path

import numpy as np
import rasterio
from rasterio.warp import transform as warp_transform

EARTH_R_M = 6371000.0
COVERAGE_M = 750.0

HERE = Path(__file__).resolve().parent


def haversine_m(lon1, lat1, lon2, lat2):
    """Great-circle distance in meters. Inputs in degrees; broadcasting OK."""
    lon1, lat1, lon2, lat2 = map(np.radians, (lon1, lat1, lon2, lat2))
    dlon, dlat = lon2 - lon1, lat2 - lat1
    a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2
    return 2 * EARTH_R_M * np.arcsin(np.sqrt(np.clip(a, 0, 1)))


def fire_pixel_centers(tif_path):
    """Annotated fire-pixel centers (lon, lat in degrees) from a 20 m mask."""
    with rasterio.open(tif_path) as s:
        mask = s.read(1)
        rows, cols = np.nonzero((mask > 0) & (mask != 255))  # 255 = nodata
        xs, ys = rasterio.transform.xy(s.transform, rows, cols,
                                       offset="center")
        lons, lats = warp_transform(s.crs, "EPSG:4326", xs, ys)
    return np.asarray(lons, float), np.asarray(lats, float)


def load_detections(csv_path):
    """Detection points (lon, lat) with the detector threshold applied."""
    lons, lats = [], []
    with open(csv_path, newline="") as f:
        for row in csv.DictReader(f):
            if "detected" in row and row["detected"].strip().lower() not in (
                    "true", "1", "1.0"):
                continue
            lons.append(float(row["lon"]))
            lats.append(float(row["lat"]))
    return np.asarray(lons, float), np.asarray(lats, float)


def coverage_fraction(fire_lonlat, det_lonlat):
    flon, flat, dlon, dlat = (*fire_lonlat, *det_lonlat)
    if len(dlon) == 0:
        return 0.0
    # (n_fire, n_det) distance matrix via broadcasting; scenes are small
    d = haversine_m(flon[:, None], flat[:, None], dlon[None, :], dlat[None, :])
    return float((d.min(axis=1) <= COVERAGE_M).mean())


def main():
    ann = sorted((HERE / "annotations").glob("*_fire_mask_20m.tif"))
    print(f"{'scene':<28}{'fire_px':>8}  {'ours_N':>7} {'ours_cov':>9}"
          f"  {'op_N':>6} {'op_cov':>7}")
    for tif in ann:
        sid = tif.name.split("_fire_mask")[0]
        fire = fire_pixel_centers(tif)
        rows = []
        for sub, tag in (("ours_negcap1", "ours"), ("viirs_official", "op")):
            f = HERE / "detections" / sub / f"{sid}_{'' if tag == 'ours' else 'official_'}detpoints.csv"
            det = load_detections(f) if f.exists() else (np.array([]), np.array([]))
            rows.append((len(det[0]), coverage_fraction(fire, det)))
        print(f"{sid:<28}{len(fire[0]):>8}  {rows[0][0]:>7} {rows[0][1]:>8.1%}"
              f"  {rows[1][0]:>6} {rows[1][1]:>7.1%}")


if __name__ == "__main__":
    main()
