#!/usr/bin/env python3
"""Reproduce the 2025 DPE atlas from public ADEME aggregates, without addresses.

Run with Python 3 (standard library only):
  python scripts/editorial-2026-12/build_dpe_atlas.py
Rebuild the frozen publication without querying a changing API:
  python scripts/editorial-2026-12/build_dpe_atlas.py --snapshot PATH_TO_SNAPSHOT

The unit is a DPE record currently exposed by the source, not a unique dwelling.
No status field is exposed: this script does not claim independent validation
of cancellations or replacements, and never treats numero_dpe_remplace as a
flag for an invalid current record (it identifies the previous report).
"""

import argparse
import csv
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

API = "https://data.ademe.fr/data-fair/api/v1/datasets/dpe03existant"
SOURCE_PAGE = "https://data.ademe.fr/datasets/meg-83tjwtg8dyz4vv7h1dqe"
GEO_API = "https://geo.api.gouv.fr/departements?fields=nom,code"
YEAR = 2025
MIN_RATE_DENOMINATOR = 100
CLASSES = tuple("ABCDEFG")
TYPES = ("maison", "appartement")
METRO_CODES = {f"{n:02d}" for n in range(1, 96) if n != 20} | {"2A", "2B"}
DATE_QUERY = f"date_etablissement_dpe:[{YEAR}-01-01 TO {YEAR}-12-31]"
HOUSING_QUERY = DATE_QUERY + " AND type_batiment:(maison OR appartement)"
VALID_QUERY = HOUSING_QUERY + " AND etiquette_dpe:(A OR B OR C OR D OR E OR F OR G)"
METRO_QUERY = VALID_QUERY + " AND code_departement_ban:(" + " OR ".join(sorted(METRO_CODES)) + ")"
STEM = "atlas-dpe-2025-departements"


def get_json(url):
    req = Request(url, headers={"User-Agent": "DevisDiagnostics-EditorialAtlas/1.0"})
    try:
        with urlopen(req, timeout=60) as response:
            return json.load(response)
    except HTTPError as exc:
        if exc.code == 429:
            raise RuntimeError("ADEME rate limit reached. Retry later; no partial atlas was published.") from exc
        raise


def query(path, params):
    url = API + path + "?" + urlencode(params)
    return url, get_json(url)


def assert_complete(node):
    if node.get("total_other", 0) != 0:
        raise AssertionError("Truncated aggregation: some groups are not returned")
    values = [str(child.get("value")) for child in node.get("aggs", [])]
    if len(values) != len(set(values)):
        raise AssertionError("Duplicate aggregation keys")
    for child in node.get("aggs", []):
        assert_complete(child)


def acquire():
    metadata = get_json(API)
    names = {row["code"]: row["nom"] for row in get_json(GEO_API)}
    requested = []

    def call(path, params):
        url, data = query(path, params)
        requested.append(url)
        return data

    by_type = call("/values_agg", {"field": "type_batiment", "agg_size": 10, "size": 0, "qs": DATE_QUERY})
    housing_total = call("/lines", {"size": 0, "qs": HOUSING_QUERY})["total"]
    aggregate = call("/values_agg", {
        "field": "code_departement_ban,type_batiment,etiquette_dpe",
        "agg_size": "200,3,7", "size": 0, "qs": VALID_QUERY,
    })
    control_total = call("/lines", {"size": 0, "qs": METRO_QUERY})["total"]
    metadata_after = get_json(API)
    if metadata_after.get("dataUpdatedAt") != metadata.get("dataUpdatedAt"):
        raise AssertionError("The source changed during extraction; rerun against one snapshot")
    return {
        "extracted_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "data_updated_at": metadata.get("dataUpdatedAt"),
        "dataset_id": metadata["id"],
        "dataset_title": metadata["title"],
        "dataset_page": SOURCE_PAGE,
        "dataset_api": API,
        "license": "Licence Ouverte / Open Licence 2.0",
        "year_of_establishment": YEAR,
        "department_names_source": GEO_API,
        "department_names": names,
        "minimum_rate_denominator": MIN_RATE_DENOMINATOR,
        "queries": requested,
        "source_exposes_status_field": any(field["key"] == "statut" for field in metadata["schema"]),
        "by_type_all_2025": by_type,
        "housing_2025_before_grade_and_department_filters": housing_total,
        "aggregate": aggregate,
        "independent_metropolitan_total": control_total,
    }


def build(snapshot, output_dir):
    assert snapshot["year_of_establishment"] == YEAR
    assert_complete(snapshot["aggregate"])
    assert_complete(snapshot["by_type_all_2025"])
    counts = {}
    grouped_housing = 0
    for department in snapshot["aggregate"]["aggs"]:
        code = str(department["value"])
        grouped_housing += department["total"]
        if code not in METRO_CODES:
            continue
        child_sum = sum(node["total"] for node in department.get("aggs", []))
        assert child_sum == department["total"], (code, "missing dwelling type")
        for typ in department["aggs"]:
            name = typ["value"]
            assert name in TYPES
            grades = {grade["value"]: grade["total"] for grade in typ["aggs"]}
            assert set(grades) <= set(CLASSES)
            assert sum(grades.values()) == typ["total"], (code, name, "missing energy label")
            counts[(code, name)] = grades

    rows = []
    total_by_type = {typ: {grade: 0 for grade in CLASSES} for typ in TYPES}
    for code in sorted(METRO_CODES):
        for typ in TYPES:
            grades = counts.get((code, typ), {})
            n = sum(grades.values())
            fg = grades.get("F", 0) + grades.get("G", 0)
            row = {
                "annee_etablissement": YEAR,
                "extraction_utc": snapshot["extracted_at"],
                "mise_a_jour_source": snapshot["data_updated_at"],
                "code_departement": code,
                "nom_departement": snapshot["department_names"].get(code, code),
                "type_batiment": typ,
                "nombre_dpe": n,
                **{f"nombre_{grade}": grades.get(grade, 0) for grade in CLASSES},
                "nombre_FG": fg,
                "part_FG_pourcent": round(100 * fg / n, 2) if n >= MIN_RATE_DENOMINATOR else "",
                "taux_publie": "oui" if n >= MIN_RATE_DENOMINATOR else "non_effectif_inferieur_100",
                "unite": "enregistrement_DPE_source_courante",
            }
            assert sum(row[f"nombre_{grade}"] for grade in CLASSES) == row["nombre_dpe"]
            for grade in CLASSES:
                total_by_type[typ][grade] += row[f"nombre_{grade}"]
            rows.append(row)

    selected_total = sum(row["nombre_dpe"] for row in rows)
    assert selected_total == snapshot["independent_metropolitan_total"], "Independent API total mismatch"
    assert len(rows) == 192
    national = []
    for typ, grades in total_by_type.items():
        n = sum(grades.values())
        fg = grades["F"] + grades["G"]
        national.append({"type_batiment": typ, "nombre_dpe": n, **grades,
                         "nombre_FG": fg, "part_FG_pourcent": round(100 * fg / n, 2)})
    summary = {
        "extracted_at": snapshot["extracted_at"],
        "data_updated_at": snapshot["data_updated_at"],
        "period": "2025-01-01/2025-12-31",
        "geography": "France metropolitaine, 96 departements",
        "counting_unit": "DPE records currently exposed by ADEME, not unique dwellings",
        "selected_total": selected_total,
        "all_2025_types_total": snapshot["by_type_all_2025"]["total"],
        "housing_before_grade_and_geography_filters": snapshot["housing_2025_before_grade_and_department_filters"],
        "housing_without_A_G_label": snapshot["housing_2025_before_grade_and_department_filters"] - snapshot["aggregate"]["total"],
        "housing_without_a_grouped_department": snapshot["aggregate"]["total"] - grouped_housing,
        "excluded_non_metropolitan_or_unlocated_A_G": snapshot["aggregate"]["total"] - selected_total,
        "national_by_type": national,
        "department_rows": rows,
        "rates_suppressed_below": MIN_RATE_DENOMINATOR,
        "checks": {"no_truncated_aggregations": True, "all_labels_reconcile": True,
                   "independent_count_reconciles": True, "stable_source_update_during_extraction": True},
        "limits": [
            "The current public dataset does not expose a status field. No independent exhaustive audit of cancelled or replaced records is claimed.",
            "A value in numero_dpe_remplace identifies the previous DPE, not invalidity of the current DPE. No such records are excluded by this script.",
            "A new extraction can differ because of source corrections, cancellations, replacements or label updates. This is not a frozen historical picture of labels in 2025.",
            "DPE records are not a representative sample of the housing stock and are not deduplicated as unique dwellings.",
            "Apartment reports generated from collective-building data remain apartment records; whole-building DPE records are excluded.",
            "No reweighting, ranking of the housing stock, causal explanation or projection of future DPE rules is performed.",
        ],
    }
    output_dir.mkdir(parents=True, exist_ok=True)
    csv_path = output_dir / f"{STEM}.csv"
    with csv_path.open("w", encoding="utf-8-sig", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]), delimiter=",")
        writer.writeheader()
        writer.writerows(rows)
    summary["csv_sha256"] = hashlib.sha256(csv_path.read_bytes()).hexdigest()
    (output_dir / f"{STEM}-snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2) + "\n")
    (output_dir / f"{STEM}-resultats.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
    print(json.dumps({key: value for key, value in summary.items() if key != "department_rows"}, ensure_ascii=False, indent=2))
    return summary


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--snapshot", type=Path, help="Use the frozen API aggregates instead of making network requests")
    parser.add_argument("--output-dir", type=Path,
                        default=Path(__file__).resolve().parents[2] / "public/downloads/editorial-2026-12")
    args = parser.parse_args()
    snapshot = json.loads(args.snapshot.read_text()) if args.snapshot else acquire()
    build(snapshot, args.output_dir)
