#!/usr/bin/env python3
"""Offline, synthetic delivery-promise decision exercise. Python 3.9+.
No HTTP, accounts, orders, real addresses, carrier data or provider tests.
The invented holiday is NOT an assertion about any real holiday calendar.
"""
from copy import deepcopy
from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
import json
from zoneinfo import ZoneInfo

RULE = {
    "version": "fictional-v1", "origin_tz": "America/New_York",
    "cutoff": "15:00", "handling_days": 1,
    "handling_weekdays": [0, 1, 2, 3, 4],
    "transit_weekdays": [0, 1, 2, 3, 4],
    "handling_closed": ["2026-11-16"],
    "transit_closed": ["2026-11-16"],
    "transit_by_zone": {"ZONE_A": 2, "ZONE_B": 4},
}
CONTEXT = {"sku": "DEMO-SKU", "quantity": 1, "zone": "ZONE_A",
           "service": "standard", "member": False, "currency": "USD",
           "surface": "authorized-demo-page"}

def business_day(d, weekdays, closed):
    return d.weekday() in weekdays and d.isoformat() not in closed

def add_days(d, count, weekdays, closed):
    # Exclude d itself; count only subsequent allowed dates.
    for _ in range(count):
        d += timedelta(days=1)
        while not business_day(d, weekdays, closed):
            d += timedelta(days=1)
    return d

def expected_by(at, rule, context):
    instant = datetime.fromisoformat(at)
    if instant.tzinfo is None:
        raise ValueError("Explicit timezone offset required")
    local = instant.astimezone(ZoneInfo(rule["origin_tz"]))
    d = local.date()
    hw, hc = rule["handling_weekdays"], rule["handling_closed"]
    # This exercise defines equality to cutoff as AFTER cutoff.
    if local.time().replace(tzinfo=None) >= time.fromisoformat(rule["cutoff"]) or not business_day(d, hw, hc):
        d += timedelta(days=1)
        while not business_day(d, hw, hc):
            d += timedelta(days=1)
    eligible = d  # day zero; handling adds subsequent business days
    shipped = add_days(eligible, rule["handling_days"], hw, hc)
    arrives = add_days(shipped, rule["transit_by_zone"][context["zone"]], rule["transit_weekdays"], rule["transit_closed"])
    return {"origin_local": local.isoformat(), "eligible_day": eligible.isoformat(),
            "ship_day": shipped.isoformat(), "expected_by": arrives.isoformat()}

def observation(at, promised, **changes):
    return {"at": at, "displayed_by": promised, "context": dict(CONTEXT, **changes)}

def fixture():
    before = "2026-11-13T19:59:00+00:00"  # 14:59 at the NY origin
    later = "2026-11-13T20:30:00+00:00"
    cases = []
    def add(name, obs, rule=None, context=None):
        cases.append({"case": name, "rule": deepcopy(rule or RULE),
                      "expected_context": dict(context or CONTEXT), "observations": obs})
    add("before_cutoff", [observation(before, "2026-11-19")])
    add("at_cutoff", [observation("2026-11-13T20:00:00+00:00", "2026-11-20")])
    add("ny_same_instant", [observation(later, "2026-11-20")])
    la = dict(RULE, origin_tz="America/Los_Angeles")
    add("la_same_instant", [observation(later, "2026-11-19")], rule=la)
    add("different_postal_zone", [observation(before, "2026-11-23", zone="ZONE_B")], context=dict(CONTEXT, zone="ZONE_B"))
    no_holiday = dict(RULE, handling_closed=[], transit_closed=[])
    add("without_invented_closure", [observation(before, "2026-11-18")], rule=no_holiday)
    add("confirmed_later_promise", [observation("2026-11-13T19:50:00+00:00", "2026-11-20"), observation("2026-11-13T19:55:00+00:00", "2026-11-20")])
    add("single_later_promise", [observation(before, "2026-11-20")])
    add("missing_promise", [observation(before, None)])
    add("wrong_service", [observation(before, "2026-11-19", service="express")])
    add("country_without_postal_zone", [observation(before, "2026-11-19", zone="UNKNOWN")], context=dict(CONTEXT, zone="UNKNOWN"))
    cases[-1]["observed_network_country"] = "US"  # deliberately cannot fill the destination zone
    return cases

def classify(case):
    evaluated = []
    for obs in case["observations"]:
        if obs["context"] != case["expected_context"] or obs["displayed_by"] is None:
            return {"case": case["case"], "decision": "unknown", "reason": "missing date or mismatched context"}
        try:
            calculated = expected_by(obs["at"], case["rule"], obs["context"])
            delta = (date.fromisoformat(obs["displayed_by"]) - date.fromisoformat(calculated["expected_by"])).days
        except (ValueError, KeyError):
            return {"case": case["case"], "decision": "unknown", "reason": "invalid date, timezone input or unmapped zone"}
        evaluated.append(dict(calculated, observed_at=obs["at"], observed_instant=datetime.fromisoformat(obs["at"]).astimezone(timezone.utc).isoformat(), displayed_by=obs["displayed_by"], delta_calendar_days=delta))
    if not evaluated:
        return {"case": case["case"], "decision": "unknown", "reason": "no observations"}
    if all(x["delta_calendar_days"] == 0 for x in evaluated):
        decision = "expected"
    elif len({x["observed_instant"] for x in evaluated}) >= 2 and all(x["delta_calendar_days"] >= 1 for x in evaluated):
        decision = "human_review"
    else:
        decision = "recheck"
    return {"case": case["case"], "decision": decision, "observations": evaluated}

def main():
    cases = fixture()
    result = [classify(c) for c in cases]
    observed = {x["case"]: x["decision"] for x in result}
    expected = dict.fromkeys(["before_cutoff", "at_cutoff", "ny_same_instant", "la_same_instant", "different_postal_zone", "without_invented_closure"], "expected")
    expected.update(confirmed_later_promise="human_review", single_later_promise="recheck", missing_promise="unknown", wrong_service="unknown", country_without_postal_zone="unknown")
    assert observed == expected, (observed, expected)
    # Independent calendar checkpoints, including weekend and fictional closure.
    by_name = {x["case"]: x for x in result}
    assert by_name["before_cutoff"]["observations"][0]["ship_day"] == "2026-11-17"
    assert by_name["at_cutoff"]["observations"][0]["expected_by"] == "2026-11-20"
    assert by_name["different_postal_zone"]["observations"][0]["expected_by"] == "2026-11-23"
    # Losing confirmation must remove escalation; duplicated timestamp is not a second check.
    c = deepcopy(cases[6]); c["observations"] = c["observations"][:1]
    assert classify(c)["decision"] == "recheck"
    c = deepcopy(cases[6]); c["observations"][1]["at"] = c["observations"][0]["at"]
    assert classify(c)["decision"] == "recheck"
    c = deepcopy(cases[6]); c["observations"][1]["at"] = "2026-11-13T14:50:00-05:00"
    assert classify(c)["decision"] == "recheck"
    c = deepcopy(cases[0]); c["observations"][0]["at"] = "2026-11-13T14:59:00"
    assert classify(c)["decision"] == "unknown"
    cost = Decimal("150")
    assert cost / 3 == Decimal("50") and cost / 6 == Decimal("25")
    print(json.dumps({"synthetic_only": True, "python_minimum": "3.9", "cases": result,
        "counts": {d: sum(x["decision"] == d for x in result) for d in ["expected", "human_review", "recheck", "unknown"]},
        "counterexamples": "PASS: removed check, duplicate timestamp, equivalent instant with different offset, missing timezone",
        "hypothetical_monthly_cost": {"incremental_USD": 150, "at_3_accepted_cases_USD_each": 50, "at_6_accepted_cases_USD_each": 25},
        "limits": "Calendar-rule exercise, not a platform replica, carrier forecast or live proxy test. No actual delivery or revenue is measured."}, indent=2))

if __name__ == "__main__":
    main()
