"""Export only the publishable A3 aggregate; never reads a database or raw feeds.

Usage: python3 scripts/export-traffic.py /path/to/figures/evaluation_hourly_profile.csv [--output result.json]
The committed JSON is used for normal builds; this script is only for provenance.
"""
import csv
import argparse
import hashlib
import json
from collections import defaultdict
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

parser = argparse.ArgumentParser(description="Export the observation-weighted A3 weekday/weekend aggregate.")
parser.add_argument("source", type=Path, help="Corrected evaluation_hourly_profile.csv")
parser.add_argument("--output", type=Path, help="Output JSON; defaults to the portfolio's public aggregate")
args = parser.parse_args()
source = args.source
rows = [row for row in csv.DictReader(source.open())
        if row["road"] == "A3" and row["direction"] == "outboundFromTown"]
assert len(rows) <= 168, "At most seven weekdays × 24 hours"
assert len({(r['weekday_number'], r['local_hour']) for r in rows}) == len(rows)
groups = defaultdict(list)
for row in rows:
    assert int(row["observations"]) > 0
    assert Decimal(row["average_speed_kmh"]) > 0
    groups[("weekdays" if int(row["weekday_number"]) <= 5 else "weekend",
            int(row["local_hour"]))].append(row)

series = {}
for day_type in ("weekdays", "weekend"):
    series[day_type] = []
    for hour in range(24):
        group = groups[day_type, hour]
        observations = sum(int(row["observations"]) for row in group)
        speed = sum(Decimal(row["average_speed_kmh"]) * int(row["observations"])
                    for row in group) / observations if observations else None
        series[day_type].append({"hour": hour,
            "speedKmh": float(speed.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)) if speed is not None else None,
            "observations": observations})

data = {
    "road": "A3", "direction": "outboundFromTown",
    "period": {"start": "2026-07-23T16:23:00+02:00", "end": "2026-09-03T19:13:00+02:00"},
    "timeZone": "Europe/Luxembourg", "unit": "km/h",
    "source": {"file": source.name, "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
        "figure": "Thesis section 6.4.1, figure 6.4",
        "method": "Observation-weighted mean of weekday/hour mean speeds; Monday–Friday versus Saturday–Sunday. Rounded to 0.1 km/h after aggregation.",
        "filters": "A3; stored direction outboundFromTown; source SQL keeps speed_kmh > 0, flow_rate > 0, occupancy_pct > 0.",
        "limits": "Historical sample, not live traffic or a forecast. Source has collection gaps; stored direction labels were not independently verified geographically."},
    "series": series,
}
target = args.output or Path(__file__).resolve().parents[1] / "public/data/a3-hourly.json"
target.parent.mkdir(exist_ok=True, parents=True)
target.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
print(f"Exported {sum(map(len, series.values()))} aggregate points to {target}")
