"""Prepare a reproducible NAIP photo sample, then summarize its reviewed labels."""

import argparse
from contextlib import ExitStack
import csv
import json
import math
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw
from pyproj import Transformer
import rasterio
from rasterio.features import geometry_mask
from rasterio.windows import Window
import requests
import shapely
from shapely.geometry import Point, shape

DATA = Path(__file__).resolve().parents[1] / "site" / "data"
PHOTO = DATA / "photo-check"
STAC = "https://planetarycomputer.microsoft.com/api/stac/v1"
SIGN = "https://planetarycomputer.microsoft.com/api/sas/v1/sign"
DATE = "2025-08-09"
SEED = 20261126
COUNT = 120


def read_json(url, params):
    result = requests.get(url, params=params, timeout=40)
    result.raise_for_status()
    return result.json()


def point_set(boundary, crs):
    forward = Transformer.from_crs(4326, crs.to_wkt(), always_xy=True)
    inverse = Transformer.from_crs(crs.to_wkt(), 4326, always_xy=True)
    area = shapely.transform(boundary, forward.transform, interleaved=False)
    xmin, ymin, xmax, ymax = area.bounds
    generator = np.random.Generator(np.random.PCG64(SEED))
    points = []
    while len(points) < COUNT:
        x, y = generator.uniform((xmin, ymin), (xmax, ymax))
        if area.contains(Point(x, y)):
            points.append(inverse.transform(x, y))
    return points


def prepare():
    boundary = shape(json.loads((DATA / "chatham-boundary.geo.json").read_text(encoding="utf-8-sig"))["geometry"])
    with rasterio.open(DATA / "canopy-source-2025.tif") as model:
        points = point_set(boundary, model.crs)
    photos = read_json(STAC + "/search", {
        "collections": "naip", "bbox": ",".join(map(str, boundary.bounds)),
        "datetime": f"{DATE}T00:00:00Z/{DATE}T23:59:59Z", "limit": 50,
    })["features"]
    if not photos or any(item["properties"]["gsd"] != 0.6 for item in photos):
        raise ValueError("Expected the 0.6 m NAIP collection for the fixed acquisition date")
    PHOTO.mkdir(exist_ok=True)
    with ExitStack() as stack:
        stack.enter_context(rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_TIMEOUT="30"))
        tiles = []
        for item in sorted(photos, key=lambda item: item["id"]):
            original = item["assets"]["image"]["href"]
            signed = read_json(SIGN, {"href": original})["href"]
            dataset = stack.enter_context(rasterio.open(signed))
            project = Transformer.from_crs(4326, dataset.crs, always_xy=True)
            tiles.append((item, dataset, project))

        entries = []
        for index, (lon, lat) in enumerate(points, 1):
            candidates = []
            for item, tile, project in tiles:
                col, row = ~tile.transform * project.transform(lon, lat)
                margin = min(col, row, tile.width - col, tile.height - row)
                if margin >= 50:
                    candidates.append((margin, item, tile, col, row))
            if not candidates:
                raise ValueError(f"No full aerial chip for point {index}")
            _, item, tile, col, row = max(candidates, key=lambda option: option[0])
            size = 96
            left, top = math.floor(col) - size // 2, math.floor(row) - size // 2
            colors = tile.read([1, 2, 3], window=Window(left, top, size, size))
            if colors.shape != (3, size, size) or not colors.any():
                raise ValueError(f"Unreadable source chip for point {index}")
            chip = Image.fromarray(colors.transpose(1, 2, 0)).resize((144, 144), Image.Resampling.NEAREST)
            draw = ImageDraw.Draw(chip)
            cx, cy = round((col - left) * 1.5), round((row - top) * 1.5)
            crosshair = [(cx - 12, cy, cx - 4, cy), (cx + 4, cy, cx + 12, cy),
                         (cx, cy - 12, cx, cy - 4), (cx, cy + 4, cx, cy + 12)]
            for stroke in crosshair:
                draw.line(stroke, fill="#252023", width=3)
                draw.line(stroke, fill="#fffaf1", width=1)
            batch_index = (index - 1) % 20
            if batch_index == 0:
                sheet = Image.new("RGB", (780, 684), "#f4f1e9")
                labels = ImageDraw.Draw(sheet)
            left, top = batch_index % 5 * 156 + 6, batch_index // 5 * 171 + 4
            sheet.paste(chip, (left, top))
            labels.text((left + 4, top + 147), f"{index:03d}", fill="#183b2d", font_size=15)
            if batch_index == 19:
                sheet.save(PHOTO / f"naip-sheet-{index // 20:02d}.jpg", quality=93, subsampling=0)
            entries.append({"id": f"{index:03d}", "lon": f"{lon:.9f}", "lat": f"{lat:.9f}", "tile": item["id"]})
        with (PHOTO / "locations.csv").open("w", newline="", encoding="utf-8") as output:
            writer = csv.DictWriter(output, fieldnames=list(entries[0]))
            writer.writeheader()
            writer.writerows(entries)
        archive = [{"id": item["id"], "datetime": item["properties"]["datetime"],
                    "gsd": item["properties"]["gsd"], "href": item["assets"]["image"]["href"]}
                   for item, _, _ in tiles]
        (PHOTO / "tiles.json").write_text(json.dumps(archive, indent=2) + "\n", encoding="utf-8")
        print(f"{len(entries)} fixed points from {len(tiles)} NAIP tiles")


def write_map_points(model, project, positions, points):
    boundary = shape(json.loads((DATA / "chatham-boundary.geo.json").read_text(encoding="utf-8-sig"))["geometry"])
    area = shapely.transform(boundary, project.transform, interleaved=False)
    rows, columns = np.nonzero(geometry_mask([area], model.shape, model.transform, all_touched=True, invert=True))
    left, top = int(columns.min()), int(rows.min())
    project_to_pixel = ~model.transform
    map_points = []
    for point, position in zip(points, positions, strict=True):
        column, row = project_to_pixel * position
        map_points.append({
            "id": point["id"], "x": round(column - left, 3), "y": round(row - top, 3),
            "cover": point["photo_class"], "modeled": point["modeled_pct"],
        })
    payload = {"width": int(columns.max()) - left + 1, "height": int(rows.max()) - top + 1, "points": map_points}
    (PHOTO / "map-points.js").write_text(
        "window.CHATHAM_PHOTO_POINTS = " + json.dumps(payload, separators=(",", ":")) + ";\n",
        encoding="utf-8"
    )


def summarize():
    with (PHOTO / "locations.csv").open(encoding="utf-8", newline="") as source:
        points = list(csv.DictReader(source))
    labels = (PHOTO / "labels.txt").read_text(encoding="utf-8").split()
    if len(points) != COUNT or len(labels) != COUNT or set(labels) - {"T", "N", "W", "U"}:
        raise ValueError("Expected one T, N, W or U label for every frozen point")
    with rasterio.open(DATA / "canopy-source-2025.tif") as model:
        project = Transformer.from_crs(4326, model.crs.to_wkt(), always_xy=True)
        positions = [project.transform(float(point["lon"]), float(point["lat"])) for point in points]
        values = [int(value[0]) for value in model.sample(positions)]
        if any(value > 100 for value in values):
            raise ValueError("A comparison point has no valid raster value")
        for point, label, value in zip(points, labels, values, strict=True):
            point.update(photo_class={"T": "tree", "N": "non-tree", "W": "water", "U": "uncertain"}[label],
                         modeled_pct=value)
        write_map_points(model, project, positions, points)
    with (PHOTO / "point-results.csv").open("w", newline="", encoding="utf-8") as output:
        writer = csv.DictWriter(output, fieldnames=list(points[0]))
        writer.writeheader()
        writer.writerows(points)
    counts = {label: labels.count(label) for label in "TNWU"}
    pairs = [(label == "T", value / 100) for label, value in zip(labels, values, strict=True) if label != "U"]
    observed, modeled = np.transpose(pairs)
    n = len(pairs)
    p = observed.mean()
    z = 1.95996398454
    denominator = 1 + z**2 / n
    middle = (p + z**2 / (2 * n)) / denominator
    half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denominator
    difference = observed - modeled
    paired_se = difference.std(ddof=1) / math.sqrt(n)
    summary = {
        "counts": counts, "readable": n, "photo_pct": float(100 * p),
        "photo_wilson_95_pct": [100 * (middle - half), 100 * (middle + half)],
        "photo_all_point_ambiguity_pct": [100 * counts["T"] / COUNT, 100 * (counts["T"] + counts["U"]) / COUNT],
        "all_points_model_pct": float(np.mean(values)),
        "all_point_difference_ambiguity_pp": [
            float(100 * trees / COUNT - np.mean(values)) for trees in (counts["T"], counts["T"] + counts["U"])
        ],
        "same_points_model_pct": float(100 * modeled.mean()), "paired_difference_pp": float(100 * difference.mean()),
        "paired_normal_95_pp": [float(100 * (difference.mean() - z * paired_se)),
                                float(100 * (difference.mean() + z * paired_se))],
    }
    (PHOTO / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("step", choices=["prepare", "summarize"])
    step = parser.parse_args().step
    (prepare if step == "prepare" else summarize)()
