"""Inspect the guide's saved responses locally; no API calls or GPU required."""

import csv
import json
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo


def main():
    history = json.loads(Path("history.json").read_text(encoding="utf-8"))
    detection = json.loads(Path("detection-response.json").read_text(encoding="utf-8"))
    response = json.loads(Path("forecast-response.json").read_text(encoding="utf-8"))

    people = sum(item["class_name"] == "person" for item in detection["detections"])
    print(f"{people} person detections (not arrival events)")

    prediction = response["predictions"][0]
    p10 = response["quantile_levels"].index(0.1)
    p90 = response["quantile_levels"].index(0.9)
    interval = timedelta(seconds=history["interval_seconds"])
    complete = [row for row in history["observations"] if row["coverage"] == 1]
    if not complete:
        raise ValueError("No complete observed hour for the forecast cutoff")
    last = datetime.fromisoformat(complete[-1]["timestamp_utc"])
    local_zone = ZoneInfo(history["timezone"])

    with Path("footfall-forecast.csv").open("w", newline="", encoding="utf-8") as output:
        writer = csv.writer(output)
        writer.writerow(["timestamp_utc", "timestamp_local", "forecast", "p10", "p90"])
        for step, value in enumerate(prediction["forecast"][0]):
            timestamp = last + (step + 1) * interval
            quantiles = prediction["quantiles"][0][step]
            writer.writerow([
                timestamp.isoformat(), timestamp.astimezone(local_zone).isoformat(),
                value, quantiles[p10], quantiles[p90],
            ])

    print(f"{len(prediction['forecast'][0])} forecasts -> footfall-forecast.csv")


if __name__ == "__main__":
    main()
