"""Replay a synthetic inventory feed for the CHINZY Guangzhou buying guide.

Run with Python 3.8+ (standard library only): python guangzhou-stock-replay.py
Use --inputs for the feed, buyer questions, and expected answers as JSON.
No network, current clock, external package, or business records are used.
"""
import argparse
import json
from datetime import datetime, timedelta


def instant(hour_minute):
    return datetime.fromisoformat("2026-11-10T" + hour_minute + ":00+08:00")


# The same source record is delivered again after the reservation has changed.
# Stock and reservations are counts of units, not prices or order confirmations.
FEED = [
    {"sku": "DEMO-A", "source": "ERP-1", "effective": "09:54", "received": "09:54", "on_hand": 12, "reserved": 2},
    {"sku": "DEMO-A", "source": "ERP-2", "effective": "10:00", "received": "10:01", "on_hand": 12, "reserved": 8},
    {"sku": "DEMO-A", "source": "ERP-1", "effective": "09:54", "received": "10:03", "on_hand": 12, "reserved": 2},
]
CATALOG = [{"sku": "DEMO-B", "on_display_card": 50, "printed": "2026-10-01"}]
CASES = [
    {"id": "before-update", "query": "09:58", "sku": "DEMO-A", "units": 6, "expected": ["covered", 10, "ERP-1"]},
    {"id": "late-replay", "query": "10:04", "sku": "DEMO-A", "units": 6, "expected": ["short", 4, "ERP-2"]},
    {"id": "freshness-boundary", "query": "10:10", "sku": "DEMO-A", "units": 4, "expected": ["covered", 4, "ERP-2"]},
    {"id": "expired", "query": "10:11", "sku": "DEMO-A", "units": 4, "expected": ["staff-check", None, "ERP-2"]},
    {"id": "catalog-only", "query": "10:04", "sku": "DEMO-B", "units": 6, "expected": ["staff-check", None, None]},
]
FRESHNESS_MINUTES = 10


def evaluate(case, order_by):
    query_time = instant(case["query"])
    received = [
        row for row in FEED
        if row["sku"] == case["sku"]
        and instant(row["received"]) <= query_time
        and instant(row["effective"]) <= query_time
    ]
    if not received:
        return ["staff-check", None, None]
    snapshot = max(received, key=lambda row: instant(row[order_by]))
    age = query_time - instant(snapshot["effective"])
    if age > timedelta(minutes=FRESHNESS_MINUTES):
        return ["staff-check", None, snapshot["source"]]
    available = snapshot["on_hand"] - snapshot["reserved"]
    decision = "covered" if available >= case["units"] else "short"
    return [decision, available, snapshot["source"]]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--inputs", action="store_true", help="print the full synthetic fixture and answer key")
    args = parser.parse_args()
    if args.inputs:
        print(json.dumps({
            "date": "2026-11-10", "utcOffset": "+08:00", "freshnessMinutes": FRESHNESS_MINUTES,
            "answerFields": ["decision", "available_units_or_null", "last_inventory_source_or_null"],
            "inventoryFeed": FEED, "printedCatalog": CATALOG, "buyerCases": CASES,
        }, indent=2))
        return 0

    runs = []
    for case in CASES:
        actual = evaluate(case, "effective")
        arrival_order = evaluate(case, "received")
        runs.append({
            "case": case["id"], "expected": case["expected"],
            "source_time_result": actual, "arrival_time_result": arrival_order,
        })
    passed = sum(row["source_time_result"] == row["expected"] for row in runs)
    arrival_passed = sum(row["arrival_time_result"] == row["expected"] for row in runs)
    print(json.dumps({
        "cases": runs, "total": len(runs),
        "source_time_passed": passed, "arrival_time_passed": arrival_passed,
    }, indent=2))
    return 0 if passed == len(runs) else 1


if __name__ == "__main__":
    raise SystemExit(main())
