"""Reproduce aggregate EPC findings; read CQC join counts as supplied summaries.

Usage: python build-care-epc-evidence.py evidence-pack.zip property-audit.xlsx output.json
No individual properties, service names, certificate IDs or contacts are exported.
The supplied site_key is a conservative archive proxy, not a verified building ID.
"""
import csv
import hashlib
import io
import json
import statistics
import sys
import xml.etree.ElementTree as ET
import zipfile
from collections import Counter, defaultdict
from datetime import date
from pathlib import Path


def worksheet_rows(path):
    ns = {"x": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
    with zipfile.ZipFile(path) as book:
        strings = []
        if "xl/sharedStrings.xml" in book.namelist():
            strings = ["".join(node.itertext()) for node in ET.fromstring(book.read("xl/sharedStrings.xml")).findall("x:si", ns)]
        rels = {node.attrib["Id"]: node.attrib["Target"].lstrip("/") for node in ET.fromstring(book.read("xl/_rels/workbook.xml.rels"))}
        result = {}
        for sheet in ET.fromstring(book.read("xl/workbook.xml")).find("x:sheets", ns):
            key = sheet.attrib["{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"]
            target = rels[key]
            if not target.startswith("xl/"):
                target = "xl/" + target
            rows = []
            for row in ET.fromstring(book.read(target)).findall("x:sheetData/x:row", ns):
                cells = {}
                for cell in row:
                    node = cell.find("x:v", ns)
                    value = node.text if node is not None else ""
                    if cell.attrib.get("t") == "s":
                        value = strings[int(value)]
                    elif cell.attrib.get("t") == "inlineStr":
                        value = "".join(cell.find("x:is", ns).itertext())
                    cells["".join(ch for ch in cell.attrib["r"] if ch.isalpha())] = value
                rows.append(cells)
            result[sheet.attrib["name"]] = rows
        return result


def build(pack_path, workbook_path):
    with zipfile.ZipFile(pack_path) as pack:
        audit = json.loads(pack.read("healthcare_premises_source_audit.json"))
        snapshot = audit["snapshot_date"]
        rows = list(csv.DictReader(io.TextIOWrapper(pack.open("healthcare_premises_selected_47289_epc_certificates.csv"), encoding="utf-8-sig")))
        assert len({row["cert"] for row in rows}) == len(rows), "Duplicate certificate IDs"
        latest = {}
        for row in rows:
            assert row["site_key"] and row["category"] in audit["raw_certificate_counts"]
            assert date.fromisoformat(row["lodge"]) <= date.fromisoformat(snapshot)
            key = (row["category"], row["site_key"])
            if key not in latest or (row["lodge"], row["cert"]) > (latest[key]["lodge"], latest[key]["cert"]):
                latest[key] = row
        raw_counts = Counter(row["category"] for row in rows)
        assert dict(raw_counts) == audit["raw_certificate_counts"]
        current = {row["cert"]: row for row in latest.values()}
        themes = defaultdict(lambda: defaultdict(set))
        recommendation_rows = 0
        for row in csv.DictReader(io.TextIOWrapper(pack.open("healthcare_premises_selected_440237_recommendations.csv"), encoding="utf-8-sig")):
            recommendation_rows += 1
            if row["cert"] not in current:
                continue
            assert row["category"] == current[row["cert"]]["category"]
            codes = {
                "heatingControls": {"EPC-H5", "EPC-H7", "EPC-H8"},
                "weatherCompensation": {"EPC-H8"},
                "optimumStartStop": {"EPC-H7"},
                "solarPvPrompt": {"EPC-R4"},
                "windPrompt": {"EPC-R2"},
            }
            for label, selected in codes.items():
                if row["code"] in selected:
                    themes[row["category"]][label].add(row["cert"])
        assert recommendation_rows == audit["recommendations_total"]
        categories = []
        for category in audit["raw_certificate_counts"]:
            group = [row for row in latest.values() if row["category"] == category]
            assert len(group) == audit["latest_site_proxy_counts"][category]
            bands = Counter(row["band"] for row in group)
            assert set(bands) <= {"A+", "A", "B", "C", "D", "E", "F", "G"}
            eg = sum(bands[band] for band in ("E", "F", "G"))
            categories.append({
                "category": category, "historicalCertificates": raw_counts[category],
                "latestProfiles": len(group), "eToG": eg, "eToGPercent": round(100 * eg / len(group), 2),
                "medianFloorAreaM2": statistics.median(float(row["floor_area"]) for row in group if row["floor_area"]),
                "recommendations": {label: {"profiles": len(ids), "percent": round(100 * len(ids) / len(group), 2)} for label, ids in themes[category].items()},
            })

    sheets = worksheet_rows(workbook_path)
    overview = {row.get("A"): row.get("B") for row in sheets["Executive Overview"] if row.get("A")}
    residential = {row.get("A"): row.get("B") for row in sheets["Residential EPC Signals"] if row.get("A")}
    n = int(residential["Locations with direct non-domestic EPC identifier"])
    older = int(residential["Latest direct EPC before 2024"])
    recent = int(residential["Latest direct EPC lodged 2024 onward"])
    assert older + recent == n
    return {
        "analysisDate": "2026-10-19", "snapshotDate": snapshot,
        "inputs": {"epcPackSha256": hashlib.sha256(Path(pack_path).read_bytes()).hexdigest(), "joinSummaryWorkbookSha256": hashlib.sha256(Path(workbook_path).read_bytes()).hexdigest()},
        "epcArchive": {
            "rawCertificates": len(rows), "recommendationRows": recommendation_rows,
            "latestProfiles": len(latest), "earliestLodgement": min(row["lodge"] for row in rows),
            "latestLodgement": max(row["lodge"] for row in rows), "categories": categories,
            "verification": "Recalculated from the supplied certificate/recommendation CSVs. Latest per supplied category + site_key, ordered by lodgement and certificate ID. These are address/UPRN profiles, not verified operational buildings.",
        },
        "suppliedCqcJoinSummary": {
            "locationRecords": int(overview["CQC adult-care locations"]),
            "locationsWithAnyCandidate": int(overview["Locations with any candidate evidence"]),
            "evidenceRelationships": int(overview["Certificate-to-CQC evidence relationships"]),
            "directIdentifierLocations": int(overview["Direct UPRN + postcode groups"]),
            "latestResidentialEpcLocations": n, "latestResidentialEpcBefore2024": older,
            "latestResidentialEpcFrom2024": recent, "before2024Percent": round(100 * older / n, 1),
            "verification": "Counts read and reconciled from the supplied summary workbook, not independently reproduced from a row-level CQC/EPC/DEC join. The referenced complete signal register was not included. Identifier agreement does not validate whole-building assessment scope; no named mismatch cases are published.",
        },
        "method": [
            "The two EPC classifications are kept separate; hospitals and care homes cannot be separated using that combined label.",
            "The supplied site_key is retained without assuming that it identifies a unique physical building; address variants and units can split or combine a footprint.",
            "Recommendation prevalence counts each selected code theme once per latest certificate. Heating controls uses only EPC-H5, EPC-H7 and EPC-H8; it is not every possible controls recommendation.",
            "Historical recommendations are investigation prompts; they do not establish a present defect, an uncompleted measure, feasibility or savings.",
            "The August care-registration cohort and October matched-summary population use different dates and filters; they are not a growth or change series.",
            "EPC asset ratings and DEC operational ratings are different measures. Their letters are not a numerical performance gap.",
            "No consumption, expenditure, property ownership, installation status or delivered saving is inferred from the certificates or registry matches.",
        ],
        "attribution": "Care Circle Network analysis of supplied Energy Performance of Buildings Data extracts and a separately supplied CQC-derived summary. Original public-sector data contains Crown copyright information licensed under the Open Government Licence v3.0; Care Circle calculations are independently described.",
        "licenceUrl": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
    }


if __name__ == "__main__":
    if len(sys.argv) != 4:
        raise SystemExit(__doc__)
    result = build(sys.argv[1], sys.argv[2])
    Path(sys.argv[3]).write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n")
