"""Safety Protocol Article 1 - the four risk tiers.

Every tool action is classified BEFORE it runs, not after.

    Tier 0  AUTONOMOUS   read, fetch, scan, search, draft, verify - no gate
    Tier 1  NOTIFY       write, store, publish, deploy - proceeds, records
    Tier 2  APPROVE      send, pay, delete, revoke - blocks for a human yes
    Tier 3  FORBIDDEN    vault, exfiltrate, tamper, self_modify - never

The rule that makes it safe: unknown actions go UP, never down. A read
misclassified as Tier 2 is an inconvenience. A payment misclassified as
Tier 0 is a silent failure. The asymmetry decides the default.

Pure logic. No repo imports, no network, no database, no clock beyond the
grant TTL. Self-test with:

    .venv/bin/python3 -m orchestrator.tiers
"""

from __future__ import annotations

import enum
import functools
import time


class Tier(enum.IntEnum):
    AUTONOMOUS = 0
    NOTIFY = 1
    APPROVE = 2
    FORBIDDEN = 3


TIER_LABELS = {
    Tier.AUTONOMOUS: "AUTONOMOUS",
    Tier.NOTIFY: "NOTIFY",
    Tier.APPROVE: "APPROVE",
    Tier.FORBIDDEN: "FORBIDDEN",
}

# FORBIDDEN scans EVERY stem - the most dangerous token anywhere in the name
# wins. So vault_read is Tier 3 even though read is Tier 0, and sign_key is
# Tier 3 even though sign is Tier 2.
FORBIDDEN_STEMS = (
    "vault", "exfiltrate", "disable_audit", "tamper", "self_modify",
    "tier_set", "mandate_forge", "sign_key", "master_key", "dump_secrets",
)

# Everything else is decided by the LEADING VERB, because the naming
# convention here is verb_noun (read_feeds, send_email, draft_brief).
# That is what keeps draft_email at Tier 0 while send_email is Tier 2.
APPROVE_STEMS = (
    "send", "email", "sms", "call", "sign", "pay", "charge", "purchase",
    "transfer", "refund", "invoice", "delete", "revoke", "unpublish", "cancel",
)

NOTIFY_STEMS = (
    "write", "store", "record", "create", "update", "publish", "deploy",
    "render", "notify", "queue", "stage", "schedule",
)

AUTONOMOUS_STEMS = (
    "read", "fetch", "scan", "search", "list", "survey", "draft", "verify",
    "probe", "measure", "ingest", "extract", "parse", "score", "rank",
    "drop",
    "filter",
    "dedupe",
    "normalize",
    "clean",
)

# The credential broker is INFRASTRUCTURE, not a tool. It is the one thing
# that legitimately touches the vault, and every exchange it makes is already
# a ledger row. Without this carve-out, "vault" being Tier 3 would stop the
# broker from doing its job.
BROKER_ACTIONS = frozenset({
    "broker_mint", "broker_exchange", "broker_grant", "broker_read",
    "vault_broker_read",
})

# Unknown goes UP. See the module docstring.
DEFAULT_TIER = Tier.APPROVE


def _stems(action):
    """Split an action name into lowercase word stems."""
    text = str(action or "").lower()
    for ch in ".:/-":
        text = text.replace(ch, "_")
    return [p for p in text.split("_") if p]


def classify(action, declared=None):
    """The tier for an action. Unknown goes UP; a declaration can only harden."""
    name = str(action or "").strip().lower()

    if name in BROKER_ACTIONS:
        computed = Tier.NOTIFY
    else:
        parts = _stems(name)
        joined = "_".join(parts)
        lead = parts[0] if parts else ""

        if any(s in parts or s in joined for s in FORBIDDEN_STEMS):
            computed = Tier.FORBIDDEN
        elif lead in APPROVE_STEMS:
            computed = Tier.APPROVE
        elif lead in NOTIFY_STEMS:
            computed = Tier.NOTIFY
        elif lead in AUTONOMOUS_STEMS:
            computed = Tier.AUTONOMOUS
        else:
            computed = DEFAULT_TIER

    if declared is None:
        return computed
    # A decorator can only make an action HARDER, never softer.
    return Tier(max(int(computed), int(declared)))


class TierBlocked(Exception):
    """Raised when an action needs approval it does not have."""


_GRANTS = {}


def grant(action, ttl_seconds=300.0):
    """Record a human yes for one action. Single-use - consumed by guard()."""
    _GRANTS[str(action)] = time.time() + float(ttl_seconds)


def pending_grants():
    """Outstanding grants as {action: seconds_remaining}."""
    now = time.time()
    return {a: round(t - now, 1) for a, t in _GRANTS.items() if t > now}


def _consume(action):
    expiry = _GRANTS.pop(str(action), None)
    return expiry is not None and expiry > time.time()


def guard(action, declared=None):
    """Classify an action and enforce it. Returns the tier when allowed."""
    tier = classify(action, declared)

    if tier is Tier.FORBIDDEN:
        raise TierBlocked(
            "%s is Tier 3 FORBIDDEN - not permitted even with a grant" % action
        )
    if tier is Tier.APPROVE and not _consume(action):
        raise TierBlocked(
            "%s is Tier 2 APPROVE - needs a human grant() first" % action
        )
    return tier


def tier(declared):
    """Declare a minimum tier for a function. Can only harden, never soften."""
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            guard(fn.__name__, declared)
            return fn(*args, **kwargs)
        wrapper._declared_tier = declared
        return wrapper
    return deco


def coverage(actions):
    """Classify a list of actions. Returns {action: tier_label}."""
    return {a: TIER_LABELS[classify(a)] for a in actions}


# --------------------------------------------------------------------------
# self-test - 25 checks, no pytest needed
# --------------------------------------------------------------------------
def _selftest():
    fails = []
    checks = [0]

    def check(label, cond):
        checks[0] += 1
        if not cond:
            fails.append(label)

    # --- classification by leading verb: 12 ---
    check("read_feeds -> AUTONOMOUS", classify("read_feeds") is Tier.AUTONOMOUS)
    check("draft_brief -> AUTONOMOUS", classify("draft_brief") is Tier.AUTONOMOUS)
    check("extract_claims -> AUTONOMOUS", classify("extract_claims") is Tier.AUTONOMOUS)
    check("draft_email -> AUTONOMOUS (lead verb wins)", classify("draft_email") is Tier.AUTONOMOUS)
    check("write_memory -> NOTIFY", classify("write_memory") is Tier.NOTIFY)
    check("publish_site -> NOTIFY", classify("publish_site") is Tier.NOTIFY)
    check("notify_owner -> NOTIFY", classify("notify_owner") is Tier.NOTIFY)
    check("send_email -> APPROVE", classify("send_email") is Tier.APPROVE)
    check("pay_invoice -> APPROVE", classify("pay_invoice") is Tier.APPROVE)
    check("delete_record -> APPROVE", classify("delete_record") is Tier.APPROVE)
    check("vault_read -> FORBIDDEN (read is 0, vault wins)", classify("vault_read") is Tier.FORBIDDEN)
    check("sign_key -> FORBIDDEN (sign is 2, sign_key wins)", classify("sign_key") is Tier.FORBIDDEN)

    # --- default up: 1 ---
    check("unknown -> APPROVE (default up)", classify("frobnicate_widget") is Tier.APPROVE)

    # --- broker carve-out: 1 ---
    check("broker_mint -> NOTIFY (infrastructure)", classify("broker_mint") is Tier.NOTIFY)

    # --- declared can only harden: 2 ---
    check("declared softer is ignored", classify("send_email", Tier.AUTONOMOUS) is Tier.APPROVE)
    check("declared harder wins", classify("read_feeds", Tier.APPROVE) is Tier.APPROVE)

    # --- guard: 6 ---
    try:
        guard("read_feeds")
        check("guard allows Tier 0", True)
    except TierBlocked:
        check("guard allows Tier 0", False)

    try:
        guard("send_email")
        check("guard blocks Tier 2 without grant", False)
    except TierBlocked:
        check("guard blocks Tier 2 without grant", True)

    grant("send_email")
    try:
        guard("send_email")
        check("guard allows Tier 2 with grant", True)
    except TierBlocked:
        check("guard allows Tier 2 with grant", False)

    try:
        guard("send_email")
        check("grant is single-use", False)
    except TierBlocked:
        check("grant is single-use", True)

    try:
        guard("vault_read")
        check("guard blocks Tier 3", False)
    except TierBlocked:
        check("guard blocks Tier 3", True)

    grant("vault_read")
    try:
        guard("vault_read")
        check("Tier 3 ignores a grant", False)
    except TierBlocked:
        check("Tier 3 ignores a grant", True)

    # --- decorator: 3 ---
    @tier(Tier.AUTONOMOUS)
    def read_soft():
        return "ok"

    check("decorator on a Tier 0 name runs", read_soft() == "ok")

    @tier(Tier.AUTONOMOUS)
    def send_thing():
        return "sent"

    try:
        send_thing()
        check("decorator cannot soften a Tier 2 name", False)
    except TierBlocked:
        check("decorator cannot soften a Tier 2 name", True)

    check("decorator stamps _declared_tier",
          getattr(read_soft, "_declared_tier", None) is Tier.AUTONOMOUS)

    # --- coverage helper: 1 ---
    cov = coverage(["read_feeds", "send_email", "vault_read"])
    check("coverage maps three actions",
          cov == {"read_feeds": "AUTONOMOUS", "send_email": "APPROVE", "vault_read": "FORBIDDEN"})

    if fails:
        print("SELFTEST FAIL (%d/%d)" % (checks[0] - len(fails), checks[0]))
        for f in fails:
            print("  FAIL", f)
        return 1
    print("SELFTEST PASS (%d checks)" % checks[0])
    return 0


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


def explain(action):
    """Why an action landed on its tier - so a classification is never opaque."""
    a = (action or "").strip().lower()
    for tier, stems in ((Tier.FORBIDDEN, FORBIDDEN_STEMS),
                        (Tier.APPROVE, APPROVE_STEMS),
                        (Tier.NOTIFY, NOTIFY_STEMS),
                        (Tier.AUTONOMOUS, AUTONOMOUS_STEMS)):
        for stem in stems:
            if stem in a:
                return "matched '%s' -> %s" % (stem, tier.name)
    return "no verb matched -> defaulted UP to %s" % DEFAULT_TIER.name
