#!/usr/bin/env python3
"""collapse_styles.py — ONE film when every style produced the identical selection.

With one candidate per window the assignment is forced, so every style's selection is
the same cut and the per-style loops would build the same film once per style name —
measured: six byte-identical 112MB deliverables, and the operator had to ask which file
to send.

BOTH DIRECTIONS MATTER, and the second is the dangerous one. Collapsing identical
selections saves disk and confusion; failing to NOT collapse would silently drop real
style variants — the exact inverse of the defect this fixes, and worse for the
operator, because the missing films would never be noticed. So the comparison is exact:
each selection canonicalised minus only its "style" field, and ANY difference keeps the
full drawn list.

Writes styles-effective.json (just the first style) when all selections are equal;
REMOVES any existing styles-effective.json otherwise, so a re-select that produces real
variety dissolves a previous collapse by itself.

Usage: collapse_styles.py --build <project/build>
Exit 0 always (no verdict when selections are missing) · 2 bad input.
"""
from __future__ import annotations

import argparse
import json
import os
import sys


def decide(build: str) -> str | None:
    """Returns the collapse message when collapsing, else None. Pure-ish: reads build/,
    writes/removes styles-effective.json."""
    effective = os.path.join(build, "styles-effective.json")
    if os.path.isfile(effective):
        os.remove(effective)                    # recomputed from scratch every run

    drawn_path = os.path.join(build, "styles-drawn.json")
    if not os.path.isfile(drawn_path):
        return None
    drawn = json.load(open(drawn_path, encoding="utf-8"))["styles"]
    if len(drawn) < 2:
        return None

    docs = []
    for st in drawn:
        path = os.path.join(build, f"selection-{st['id']}.json")
        if not os.path.isfile(path):
            return None                         # not all selections exist; no verdict
        doc = json.load(open(path, encoding="utf-8"))
        doc.pop("style", None)
        docs.append(json.dumps(doc, sort_keys=True))
    if len(set(docs)) != 1:
        return None                            # real variety — NEVER collapse it

    json.dump({"styles": [drawn[0]], "collapsedFrom": len(drawn),
               "reason": "every style produced an identical selection — one candidate "
                         "per window leaves nothing to vary"},
              open(effective, "w", encoding="utf-8"), indent=1)
    return (f"select: the {len(drawn)} drawn styles produced IDENTICAL selections — "
            f"building ONE film ({drawn[0]['id']}) instead of {len(drawn)} copies")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--build", required=True)
    args = ap.parse_args()
    if not os.path.isdir(args.build):
        print(f"collapse_styles: no dir {args.build}", file=sys.stderr)
        raise SystemExit(2)
    msg = decide(args.build)
    if msg:
        print(msg)


if __name__ == "__main__":
    main()
