#!/usr/bin/env python3
"""Offline synthetic continuity worksheet; Python 3.9+ standard library only.

No network, DNS, secrets, credentials, provider APIs, configuration changes, or
automatic failover. Inputs are asserted planning evidence, not proof of actual
availability, authorization, independence, performance, or contractual terms.
"""
from collections import Counter


REQUIRED = ("destination", "dns", "runtime", "scheduler", "credentials")
DEPENDENCY_STATES = {"READY", "FAILED", "UNKNOWN"}
ROUTE_A_STATES = {"FAILED", "ELIGIBLE"}
ROUTE_B_STATES = {"ELIGIBLE", "FAILED", "INELIGIBLE", "UNKNOWN"}
EGRESS_STATES = {"AUTHORIZED", "NOT_AUTHORIZED", "UNKNOWN"}
SESSION_STATES = {"COMPATIBLE", "INCOMPATIBLE", "UNKNOWN"}


def job_result(case):
    """Conservatively classify one synthetic scenario for route B."""
    route_a, route_b = case["route_a"], case["route_b"]
    dependencies = case["dependencies"]
    if route_a not in ROUTE_A_STATES:
        raise ValueError("invalid route_a state")
    if route_b not in ROUTE_B_STATES:
        raise ValueError("invalid route_b state")
    if case["egress"] not in EGRESS_STATES:
        raise ValueError("invalid egress state")
    if case["session"] not in SESSION_STATES:
        raise ValueError("invalid session state")
    if set(dependencies) != set(REQUIRED):
        raise ValueError("dependencies must have exactly the required names")
    if any(state not in DEPENDENCY_STATES for state in dependencies.values()):
        raise ValueError("invalid dependency state")
    states = [dependencies[name] for name in REQUIRED]
    # A known required failure blocks the job even when another requirement is unknown.
    if ("FAILED" in states or
            route_b in {"FAILED", "INELIGIBLE"} or
            case["egress"] == "NOT_AUTHORIZED" or
            case["session"] == "INCOMPATIBLE"):
        return "NOT_POSSIBLE"
    if route_b == "UNKNOWN" or case["egress"] == "UNKNOWN" or case["session"] == "UNKNOWN":
        return "UNKNOWN"
    if route_b != "ELIGIBLE":
        return "NOT_POSSIBLE"
    if case["egress"] != "AUTHORIZED" or case["session"] != "COMPATIBLE":
        return "NOT_POSSIBLE"
    if "UNKNOWN" in states:
        return "UNKNOWN"
    return "POSSIBLE"


def cases():
    ready = dict.fromkeys(REQUIRED, "READY")
    return (
        {"name": "a_provider_failed", "route_a": "FAILED", "route_b": "ELIGIBLE",
         "dependencies": ready.copy(), "egress": "AUTHORIZED", "session": "COMPATIBLE",
         "expected": "POSSIBLE"},
        {"name": "destination_failed", "route_a": "ELIGIBLE", "route_b": "ELIGIBLE",
         "dependencies": dict(ready, destination="FAILED"), "egress": "AUTHORIZED", "session": "COMPATIBLE",
         "expected": "NOT_POSSIBLE"},
        {"name": "dns_unknown", "route_a": "ELIGIBLE", "route_b": "ELIGIBLE",
         "dependencies": dict(ready, dns="UNKNOWN"), "egress": "AUTHORIZED", "session": "COMPATIBLE",
         "expected": "UNKNOWN"},
        {"name": "backup_route_unknown", "route_a": "FAILED", "route_b": "UNKNOWN",
         "dependencies": ready.copy(), "egress": "AUTHORIZED", "session": "COMPATIBLE",
         "expected": "UNKNOWN"},
        {"name": "backup_egress_not_authorized", "route_a": "FAILED", "route_b": "ELIGIBLE",
         "dependencies": ready.copy(), "egress": "NOT_AUTHORIZED", "session": "COMPATIBLE",
         "expected": "NOT_POSSIBLE"},
        {"name": "route_bound_session", "route_a": "FAILED", "route_b": "ELIGIBLE",
         "dependencies": ready.copy(), "egress": "AUTHORIZED", "session": "INCOMPATIBLE",
         "expected": "NOT_POSSIBLE"},
    )


def run():
    results = []
    for case in cases():
        actual = job_result(case)
        if actual != case["expected"]:
            raise AssertionError((case["name"], actual, case["expected"]))
        results.append((case["name"], actual))
    # Meaningful counterexamples: unknown is not a pass; a failed shared
    # dependency and incompatible authorized-job conditions block route B.
    assert results[2][1] == results[3][1] == "UNKNOWN"
    assert results[1][1] == "NOT_POSSIBLE"
    assert results[4][1] == results[5][1] == "NOT_POSSIBLE"
    base = cases()[0]
    unknown_egress = dict(base, egress="UNKNOWN")
    unknown_session = dict(base, session="UNKNOWN")
    assert job_result(unknown_egress) == job_result(unknown_session) == "UNKNOWN"
    known_failed_plus_unknown = dict(base, dependencies=dict(base["dependencies"], dns="FAILED", runtime="UNKNOWN"))
    assert job_result(known_failed_plus_unknown) == "NOT_POSSIBLE"
    for invalid in ("BROKEN", None):
        bad_dependency = dict(base, dependencies=dict(base["dependencies"], dns=invalid))
        try:
            job_result(bad_dependency)
        except ValueError:
            pass
        else:
            raise AssertionError("invalid dependency state accepted")
    invalid_route_a = dict(base, route_a="BROKEN", route_b="UNKNOWN")
    try:
        job_result(invalid_route_a)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid route_a was hidden by unknown route_b")
    # Any known blocker wins over unrelated unknown fields.
    assert job_result(dict(base, route_b="FAILED", egress="UNKNOWN")) == "NOT_POSSIBLE"
    assert job_result(dict(base, route_b="INELIGIBLE", session="UNKNOWN")) == "NOT_POSSIBLE"
    assert job_result(dict(base, egress="NOT_AUTHORIZED", session="UNKNOWN")) == "NOT_POSSIBLE"
    assert job_result(dict(base, session="INCOMPATIBLE", egress="UNKNOWN")) == "NOT_POSSIBLE"
    return results


if __name__ == "__main__":
    results = run()
    for name, result in results:
        print("%s: %s" % (name, result))
    print("counts: %s" % dict(sorted(Counter(result for _, result in results).items())))
    print("PASS: offline synthetic cases and unknown/shared/eligibility counterexamples.")
