#!/usr/bin/env python3
"""Offline synthetic recovery ledger: no I/O, network, credentials, or production actions."""
from dataclasses import dataclass

NOW, FRESH_LIMIT = 100, 3

@dataclass(frozen=True)
class Job:
    row_id: object; planned: object; deadline: object; identity: object; kind: object
    read_only: object; replaceable: object; snapshot: object = None; scope: object = None
    fields: object = (); auth: object = None; prior: object = "none"; retained: object = False
    as_of: object = None; finish: object = None

# Deliberately unsorted. Recovery sorts only after checking IDs and planned-order ties.
JOBS = (
 Job("S-old",91,115,"snap-us-091","snapshot",True,True,"catalog-us","us",("sku","price"),"AUTH-7","none",False,None,105),
 Job("C-old",85,120,"snap-ca-085","snapshot",True,True,"catalog-ca","ca",("sku","price"),"AUTH-7","none",False,None,101),
 Job("E-uncertain",87,89,"price-087","price",True,False,None,None,(),"AUTH-7","unknown"),
 Job("S-expired",80,90,"snap-us-080","snapshot",True,True,"catalog-us","us",("sku","price"),"AUTH-7"),
 Job("H-history",92,103,"history-01","history",True,False,None,None,(),"AUTH-7","none",True,"2026-12-03T01:00Z"),
 Job("U-deadline",93,None,"snap-eu-093","snapshot",True,True,"catalog-eu","eu",("sku","price"),"AUTH-7"),
 Job("U-identity",94,112,None,"snapshot",True,True,None,"eu",("sku","price"),"AUTH-7"),
 Job("P-price",95,108,"price-us-095","price",True,False,None,None,(),"AUTH-7","none",False,None,108),
 Job("S-latest",96,116,"snap-us-096","snapshot",True,True,"catalog-us","us",("sku","price"),"AUTH-7","none",False,None,117),
 Job("M-expired",97,99,"history-old","history",True,False,None,None,(),"AUTH-7","none",True,"2026-12-02T23:00Z"),
 Job("C-expired-newer",98,99,"snap-ca-098","snapshot",True,True,"catalog-ca","ca",("sku","price"),"AUTH-7"),
 Job("S-auth-mismatch",99,119,"snap-us-099","snapshot",True,True,"catalog-us","us",("sku","price"),"AUTH-8","none",False,None,110),
 Job("S-incomplete",100,120,"snap-eu-100","snapshot",True,True,"catalog-eu",None,("sku","price"),"AUTH-7"),
 Job("B-bool",101,120,"bad-101","snapshot",1,True,"bad","us",("sku",),"AUTH-7"),
 Job("D-before",102,101,"bad-102","price",True,False,None,None,(),"AUTH-7"),
 Job("F-future",103,121,"future-103","price",True,False,None,None,(),"AUTH-7"),
 Job("T-tie-a",104,122,"tie-a","price",True,False,None,None,(),"AUTH-7"),
 Job("T-tie-b",104,122,"tie-b","price",True,False,None,None,(),"AUTH-7"),
)

def text(v): return isinstance(v, str) and bool(v.strip())
def integer(v): return type(v) is int
def key(j):
    if j.kind != "snapshot" or j.read_only is not True or j.replaceable is not True: return None
    if not (text(j.snapshot) and text(j.scope) and isinstance(j.fields, tuple) and j.fields and all(text(v) for v in j.fields) and text(j.auth)): return None
    return j.snapshot, j.scope, j.fields, j.auth

def hold_reason(j, ties):
    if not text(j.row_id): return "invalid_row_id"
    if not integer(j.planned): return "invalid_planned_type"
    if j.planned in ties: return "planned_order_tie"
    if not integer(j.deadline): return "unknown_or_invalid_deadline"
    if j.deadline < j.planned: return "deadline_before_planned"
    if not text(j.identity): return "unknown_or_invalid_identity"
    if not text(j.auth): return "unknown_or_invalid_authorization"
    if j.kind not in ("snapshot", "price", "history"): return "unknown_or_invalid_kind"
    if type(j.read_only) is not bool or type(j.replaceable) is not bool: return "invalid_boolean_flag"
    if j.read_only is not True: return "non_readonly_work"
    if j.prior != "none": return "prior_effects_uncertain"
    if j.kind == "snapshot" and j.replaceable is True and key(j) is None: return "replacement_equivalence_incomplete"
    if j.kind == "history" and not (j.retained is True and text(j.as_of) and text(j.auth)): return "historical_input_or_asof_missing"
    if j.planned > NOW: return "planned_after_recovery"
    return None

def recover(jobs):
    ids = [j.row_id for j in jobs]
    if len(ids) != len(set(ids)): raise ValueError("duplicate row_id")
    stable_ids = [j.identity for j in jobs if text(j.identity)]
    if len(stable_ids) != len(set(stable_ids)): raise ValueError("duplicate stable identity")
    plans = [j.planned for j in jobs if integer(j.planned)]
    ties = {p for p in plans if plans.count(p) > 1}
    ordered = sorted(jobs, key=lambda j: (j.planned if integer(j.planned) else 10**9, str(j.row_id)))
    states = {}
    for j in ordered:
        why = hold_reason(j, ties)
        if why: states[j.row_id] = ("HOLD", why) # HOLD deliberately precedes expiry.
        elif j.deadline < NOW: states[j.row_id] = ("EXPIRE", "deadline_passed")
        elif j.kind == "history": states[j.row_id] = ("PRESERVE_LOCAL_HISTORY", "retained_input_at_declared_asof")
        else: states[j.row_id] = ("READY", "current_readonly_work")
    latest = {}
    for j in ordered:
        if key(j) is not None and states[j.row_id][0] == "READY": latest[key(j)] = j.row_id
    for j in ordered:
        if key(j) is not None and states[j.row_id][0] == "READY" and latest[key(j)] != j.row_id: states[j.row_id] = ("COALESCE", "newer_current_equivalent_readonly_snapshot")
    ready = [j for j in ordered if states[j.row_id][0] == "READY"]
    admitted = {j.row_id for j in ready[:FRESH_LIMIT]}
    ledger = []
    for j in ordered:
        state, why = states[j.row_id]
        if state == "READY":
            if j.row_id not in admitted: state, why = "DEFERRED_CAP", "fresh_recovery_limit"
            elif not integer(j.finish) or j.finish < NOW: state, why = "HOLD", "invalid_finish_recheck"
            elif j.finish > j.deadline: state, why = "LATE_NOT_DELIVERED", "expired_at_finish"
            else: state, why = "DELIVERED_SYNTHETIC", "fresh_at_dispatch_and_finish"
        ledger.append((j, state, why))
    return ledger

def main():
    ledger = recover(JOBS); names = ("EXPIRE","COALESCE","HOLD","PRESERVE_LOCAL_HISTORY","DELIVERED_SYNTHETIC","LATE_NOT_DELIVERED","DEFERRED_CAP")
    counts = {n: sum(1 for _, state, _ in ledger if state == n) for n in names}
    print("offline_synthetic_proxy_backlog_recovery")
    print("network_requests=0 credential_reads=0 file_reads=0 production_actions=0")
    print("recovery_now=100 fresh_limit=3 planned=18 input_order=deliberately_unsorted")
    print("planned_order=" + ",".join(j.row_id for j, _, _ in ledger))
    for j, state, why in ledger: print("ledger %s=%s reason=%s" % (j.row_id, state, why))
    print("dispatch_finish C-old=100/101:ON_TIME P-price=100/108:ON_TIME S-latest=100/117:LATE")
    print("summary=" + " ".join("%s:%s" % (n, counts[n]) for n in names) + " accounted:18/18")
    assert len(ledger) == 18 and counts == {"EXPIRE":3,"COALESCE":1,"HOLD":9,"PRESERVE_LOCAL_HISTORY":1,"DELIVERED_SYNTHETIC":2,"LATE_NOT_DELIVERED":1,"DEFERRED_CAP":1}
    try:
        recover(JOBS + (Job("duplicate-stable", 70, 110, "snap-ca-085", "price", True, False, auth="AUTH-7"),))
        raise AssertionError("duplicate stable identity accepted")
    except ValueError as error:
        assert str(error) == "duplicate stable identity"
    print("guards=PASS unique_ids_sorted_planned_order_hold_precedes_expiry_expired_newer_never_suppresses_equivalence_is_exact_history_is_local_only_cap_and_finish_recheck")

if __name__ == "__main__": main()
