"""Check a proposed repair against a pinned teaching snapshot. Python 3.8+."""
import argparse
import hashlib
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

SNAPSHOT = Path("maintenance-windows.json")
SHA256 = "ed99e2041c51332c595933c3c6322365a0ffab5ebf92a395eda325432c339bd5"


def instant(value):
    if value.endswith("Z"):
        value = value[:-1] + "+00:00"
    result = datetime.fromisoformat(value)
    if result.utcoffset() is None or result.utcoffset() % timedelta(minutes=1) or result.second or result.microsecond:
        raise ValueError("Use a whole-minute timestamp with Z or an explicit UTC offset.")
    return result.astimezone(timezone.utc)


def utc(value):
    return value.isoformat(timespec="minutes").replace("+00:00", "Z")


def minutes(start, end):
    return (end - start) // timedelta(minutes=1)


def assess(windows, start, end):
    intersections = []
    spans = []
    for window in windows:
        if window["isAvailable"] is not True:
            continue
        opens, closes = instant(window["startTime"]), instant(window["endTime"])
        left, right = max(opens, start), min(closes, end)
        if left < right:
            spans.append((left, right))
            intersections.append({
                "id": window["id"], "opens_utc": utc(opens), "closes_utc": utc(closes),
                "overlap_minutes": minutes(left, right),
                "covers_whole_repair": opens <= start and end <= closes,
            })

    covered = 0
    last = start
    for left, right in sorted(spans):
        if right > last:
            covered += minutes(max(left, last), right)
            last = right
    return {
        "snapshot_sha256": SHA256, "start_utc": utc(start), "end_utc": utc(end),
        "requested_minutes": minutes(start, end), "intersections": intersections,
        "summed_window_minutes": sum(item["overlap_minutes"] for item in intersections),
        "distinct_covered_minutes": covered,
        "eligible_window_ids": [item["id"] for item in intersections if item["covers_whole_repair"]],
    }


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("start", help="ISO timestamp, e.g. 2026-01-05T04:00Z")
    cli.add_argument("minutes", type=int, help="positive whole minutes of uninterrupted work")
    cli.add_argument("report", type=Path, help="new JSON report filename")
    args = cli.parse_args()
    try:
        start = instant(args.start)
        if args.minutes <= 0:
            raise ValueError("Duration must be positive.")
        end = start + timedelta(minutes=args.minutes)
        raw = SNAPSHOT.read_bytes()
        if hashlib.sha256(raw).hexdigest() != SHA256:
            raise ValueError("Snapshot differs from the pinned Microsoft file.")
        result = assess(json.loads(raw), start, end)
        with args.report.open("x", encoding="utf-8") as out:
            print(json.dumps(result, indent=2), file=out)
    except (ValueError, OSError, OverflowError) as error:
        cli.exit(1, f"{error}\n")
    print(f"{args.report}: {len(result['eligible_window_ids'])} eligible window(s)")


if __name__ == "__main__":
    main()
