"""
What built what: code fingerprints for stages, and per-building build keys.

TWO QUESTIONS A RESUMABLE, INCREMENTAL BUILD HAS TO ANSWER, and until 24 Sep
2026 it could answer neither from the code:

1. Is this stage's marker still valid? run_stage.py compared file mtimes, so a
   CODE change never invalidated anything: fix a bug in panel_fitting.py,
   run the district build with --skip-done, and every region skipped every
   stage on its old marker. stage_code_hash() fingerprints a stage's script,
   every src module it imports (transitively), config.py and the lock file,
   and the marker records it.

2. Which buildings are stale? data/built_from.json recorded only a hash of
   each building's selected-faces reading, so a code change never made a
   building stale either, and buildings with no reading were never checked at
   all. building_key() is the reading hash PLUS the geometry code hash, for
   every building; a building is stale when its recorded key differs.

Keys live per region (data/regions/<r>/built_from.json) so fleet workers that
build different regions never write the same file. The old global file is
still read, but its entries carry no code hash, so every building it lists
reads as stale once -- correctly: nothing says which code built it.
"""

import ast
import hashlib
import re
import json
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "src"
DATA = ROOT / "data"

# The stage whose code decides a building's geometry (and everything it
# imports: segmentation, partition, panel fitting, obstructions, shading).
GEOMETRY_STAGE = "build_layout_geojson"

_closure_cache = {}


def _src_imports(path):
    """src modules imported anywhere in `path` (module level or inside
    functions -- most of this repo imports lazily)."""
    try:
        tree = ast.parse(path.read_text())
    except (OSError, SyntaxError):
        return set()
    out = set()
    for n in ast.walk(tree):
        if isinstance(n, ast.ImportFrom) and n.module:
            if n.module == "src":
                out.update(a.name for a in n.names)
            elif n.module.startswith("src."):
                out.add(n.module.split(".")[1])
        elif isinstance(n, ast.Import):
            for a in n.names:
                if a.name.startswith("src."):
                    out.add(a.name.split(".")[1])
    return {m for m in out if (SRC / f"{m}.py").exists()}


def module_closure(stage):
    """Every src module `stage` can reach through imports, itself included."""
    if stage in _closure_cache:
        return _closure_cache[stage]
    seen, todo = set(), [stage]
    while todo:
        m = todo.pop()
        if m in seen or not (SRC / f"{m}.py").exists():
            continue
        seen.add(m)
        todo.extend(_src_imports(SRC / f"{m}.py") - seen)
    _closure_cache[stage] = sorted(seen)
    return _closure_cache[stage]


def stage_code_hash(stage):
    """Hash of the code a stage runs: its closure of src modules, config.py and
    the dependency lock. Twelve hex characters. A tools/ script imported by a
    stage at runtime (face_regions -> tools/train_face_regions) is not
    followed; neither is data such as models, which stage inputs cover."""
    h = hashlib.sha256()
    for m in module_closure(stage):
        h.update(m.encode())
        h.update((SRC / f"{m}.py").read_bytes())
    for extra in (ROOT / "config.py", ROOT / "requirements.lock.txt"):
        if extra.exists():
            h.update(extra.name.encode())
            h.update(_hashed_bytes(extra))
    return h.hexdigest()[:12]


# WHERE THE BUILD RUNS IS NOT WHAT IT BUILDS. config.CLOUD_SHARED_BUILD names
# the cloud project, VM and preview bucket; no output depends on it. Hashed
# with the rest of config.py, moving the map to its own project (19 Oct 2026)
# would have marked all 39 regions stale for a 16-hour rebuild that changes
# nothing. The block is left out of the hash.
_CLOUD_BLOCK = re.compile(r"^CLOUD_SHARED_BUILD = \{\n.*?^\}\n", re.S | re.M)


def _hashed_bytes(path):
    if path.name != "config.py":
        return path.read_bytes()
    return _CLOUD_BLOCK.sub("", path.read_text(encoding="utf-8"), count=1).encode("utf-8")


def reading_hash(building_id):
    """Hash of the selected-faces reading a building is built from, or "none".
    Same 12-character md5 the original built_from.json recorded."""
    p = DATA / "selected_faces" / f"{building_id}.json"
    # an agreed reading of identical roofs replaces the building's own
    # (src/repeat_roofs.py, SOLAR_REPEAT_ROOFS)
    r = DATA / "repeat_faces" / f"{building_id}.json"
    if os.environ.get("SOLAR_REPEAT_ROOFS", "1") == "1" and r.exists():
        p = r
    # the vision referee's pick comes first when it is on (src/reading_referee.py)
    v = DATA / "referee_faces" / f"{building_id}.json"
    if os.environ.get("SOLAR_READING_REFEREE", "0") == "1" and v.exists():
        p = v
    return hashlib.md5(p.read_bytes()).hexdigest()[:12] if p.exists() else "none"


def building_key(building_id, geometry_hash=None, region=None):
    """What a building's layout is built from: its reading and the geometry
    code. Drawn markup (data/roof_labels.json) is an input too and is in the
    key through its own hash, so a newly drawn roof reads as stale. So is the
    slide that moves its outline onto the roof (src/outline_fit.py), added
    only where there is one, so every other key is unchanged."""
    k = f"{reading_hash(building_id)}+{labels_hash(building_id)}+" \
        f"{geometry_hash or stage_code_hash(GEOMETRY_STAGE)}"
    s = outline_slide(region, building_id) if region else None
    return k + (f"+s{s[0]:.2f},{s[1]:.2f}" if s else "")


_slides = {}


def outline_slide(region, building_id):
    """The accepted outline slide for a building, or None (SOLAR_OUTLINE_FIT)."""
    if os.environ.get("SOLAR_OUTLINE_FIT", "1") != "1":
        return None
    if region not in _slides:
        try:
            _slides[region] = json.loads((DATA / "regions" / region / "outline_fit.json").read_text())
        except (OSError, ValueError):
            _slides[region] = {}
    from src.outline_fit import accepted
    return accepted(_slides[region].get(str(int(building_id))))


_labels = None


def labels_hash(building_id):
    global _labels
    if _labels is None:
        try:
            _labels = json.loads((DATA / "roof_labels.json").read_text())
        except (OSError, ValueError):
            _labels = {}
        if isinstance(_labels, dict) and "buildings" in _labels:
            _labels = _labels["buildings"]
    lab = _labels.get(str(building_id)) if isinstance(_labels, dict) else None
    if lab is None:
        return "nolab"
    return hashlib.md5(json.dumps(lab, sort_keys=True).encode()).hexdigest()[:8]


def keys_path(region):
    return DATA / "regions" / region / "built_from.json"


def load_keys(region):
    try:
        return json.loads(keys_path(region).read_text())
    except (OSError, ValueError):
        return {}


def record_keys(region, building_ids, geometry_hash=None, replace=False):
    """Record the current key for these buildings (after building them).
    replace=True starts the file afresh -- a full region build, after which
    no other building's old key should survive."""
    gh = geometry_hash or stage_code_hash(GEOMETRY_STAGE)
    keys = {} if replace else load_keys(region)
    for bid in building_ids:
        keys[str(int(bid))] = building_key(int(bid), gh, region)
    p = keys_path(region)
    p.parent.mkdir(parents=True, exist_ok=True)
    tmp = p.with_name(p.name + ".tmp")
    tmp.write_text(json.dumps(keys, sort_keys=True))
    os.replace(tmp, p)


def stale_buildings(region, building_ids, geometry_hash=None):
    """The subset of building_ids whose recorded key differs from now."""
    gh = geometry_hash or stage_code_hash(GEOMETRY_STAGE)
    keys = load_keys(region)
    return [int(b) for b in building_ids if keys.get(str(int(b))) != building_key(int(b), gh, region)]


YIELD_STAGE = "apply_yield"


def yield_code_hash():
    """Hash of the code that turns geometry into kWh (the solar model and
    what it imports, config, the lock). Stamped on the layouts by whichever
    stage last computed their kWh, so a region can say which sun it used."""
    return stage_code_hash(YIELD_STAGE)


def geometry_hash_of_key(key):
    """The geometry-code part of a recorded building key, or None."""
    if not isinstance(key, str):
        return None
    parts = key.split("+")
    if len(parts) < 3 or not re.fullmatch(r"[0-9a-f]{12}", parts[2]):
        return None
    return parts[2]


def model_version(geometry_hash, yield_hash):
    """What the map shows as a building's model version: geometry and sun,
    six characters each. A building whose numbers move between two builds
    can be told apart by which half changed."""
    g = geometry_hash[:6] if geometry_hash else "unknown"
    y = yield_hash if yield_hash in ("mixed",) else (yield_hash[:6] if yield_hash else "unknown")
    return f"g{g}-y{y}"
