#!/usr/bin/env python3
"""Synthetic, offline, hours-only branch-listing reconciliation queue."""
from collections import Counter
from datetime import date

AS_OF = date(2026, 11, 24)
REQUIRED = {"branch", "same_entity", "approved_source", "observed_source", "approved_as_of",
            "observed_at", "observed_for_date", "timezone", "regular_hours", "special_date",
            "special_hours", "observed_hours", "owner"}


def parse_day(value):
    try:
        return date.fromisoformat(value)
    except (TypeError, ValueError):
        return None


def hold(reason):
    return "HOLD", reason


def expected_hours(row):
    special_day = parse_day(row["special_date"]) if row["special_date"] else None
    if special_day == AS_OF:
        # A source must explicitly say CLOSED; an empty special value is not a closure claim.
        if row["special_hours"] in ("", None):
            return None
        return row["special_hours"]
    return row["regular_hours"]


def disposition(row):
    if not isinstance(row, dict) or not REQUIRED.issubset(row):
        return hold("malformed or incomplete record")
    if row["same_entity"] is not True:
        return hold("ambiguous entity; resolve branch identity")
    if not all(isinstance(row[key], str) and row[key] for key in ("approved_source", "observed_source", "owner", "timezone")):
        return hold("missing source, owner, or timezone context")
    approved, observed, observed_for = (parse_day(row[key]) for key in ("approved_as_of", "observed_at", "observed_for_date"))
    if not all((approved, observed, observed_for)):
        return hold("malformed date evidence")
    if approved > AS_OF or observed > AS_OF:
        return hold("future-dated evidence")
    if observed_for != AS_OF:
        return hold("observation is not for the comparison date")
    if (AS_OF - approved).days > 7 or (AS_OF - observed).days > 7:
        return hold("stale evidence; refresh before changing anything")
    if not isinstance(row["regular_hours"], str) or not row["regular_hours"]:
        return hold("missing or malformed regular hours")
    if row["special_date"] and parse_day(row["special_date"]) is None:
        return hold("malformed special-hours date")
    if parse_day(row["special_date"]) == AS_OF and (
        not isinstance(row["special_hours"], str) or not row["special_hours"]
    ):
        return hold("special-hours value missing or malformed; do not infer closed")
    expected = expected_hours(row)
    if not isinstance(row["observed_hours"], str) or not row["observed_hours"]:
        return hold("missing observed hours")
    if expected == row["observed_hours"]:
        return "NO_ACTION", "same entity, same date, comparable hours agree"
    priority = "P1" if parse_day(row["special_date"]) == AS_OF else "P2"
    return priority, f"assign {row['owner']}: hours differ ({expected} vs {row['observed_hours']})"


BASE = {"same_entity": True, "approved_source": "owner-feed-v7", "observed_source": "licensed-export-A",
        "approved_as_of": "2026-11-24", "observed_at": "2026-11-24", "observed_for_date": "2026-11-24",
        "timezone": "America/New_York", "regular_hours": "09:00-17:00", "special_date": "",
        "special_hours": "", "observed_hours": "09:00-17:00", "owner": "listing-ops@example.invalid"}
ROWS = [
    ("North-01", {**BASE, "branch": "North-01", "regular_hours": "09:00-18:00", "special_date": "2026-11-24", "special_hours": "10:00-14:00", "observed_hours": "09:00-18:00"}),
    ("Central-02", {**BASE, "branch": "Central-02", "observed_hours": "10:00-17:00"}),
    ("West-03", {**BASE, "branch": "West-03", "same_entity": "true"}),
    ("Harbor-04", {**BASE, "branch": "Harbor-04", "approved_as_of": "2026-11-10"}),
    ("East-05", {**BASE, "branch": "East-05"}),
    ("Date-06", {**BASE, "branch": "Date-06", "observed_for_date": "2026-11-23"}),
    ("Future-07", {**BASE, "branch": "Future-07", "observed_at": "2026-11-25"}),
    ("Missing-08", {**BASE, "branch": "Missing-08", "observed_source": ""}),
    ("Special-09", {**BASE, "branch": "Special-09", "special_date": "2026-11-24", "special_hours": ""}),
    ("Malformed-10", ["not", "a", "record"]),
]


def main():
    print("Synthetic hours reconciliation — comparison date 2026-11-24")
    print("Assumptions: pre-approved identity; ISO dates; evidence <= 7 days; declared timezone; P1 special-hours, P2 regular-hours.")
    counts = Counter()
    for label, row in ROWS:
        state, reason = disposition(row)
        counts[state] += 1
        print(f"{label}: {state} — {reason}")
    print("Queue summary: " + ", ".join(f"{key}={counts[key]}" for key in ("P1", "P2", "HOLD", "NO_ACTION")))
    print("PASS: synthetic fixture only; no network, files, secrets, or listing edits.")


if __name__ == "__main__":
    main()
