"""
Interceptor — Full Feature Demo
================================
Exercises every feature in one script.
"""

from interceptor import Interceptor, intercept, RiskLevel
import tempfile, textwrap, time
from pathlib import Path

DIVIDER = "\n" + "=" * 60


# ── 1. STRICT MODE ──────────────────────────────────────────
print(DIVIDER)
print("  1) STRICT MODE")
print(DIVIDER)

guard = Interceptor(mode="strict")

print("\n→ LOW risk (read_file):")
d = guard.run("read_file", {"key": "config"})

print("\n→ MEDIUM risk (write_file with path):")
d = guard.run("write_file", {"path": "/tmp/output.txt", "data": "hello"})

print("\n→ HIGH risk (delete_file) as regular user:")
d = guard.run("delete_file", {"path": "/tmp/important.csv"})

print("\n→ HIGH risk (delete_file) as admin:")
d = guard.run("delete_file", {"path": "/tmp/important.csv"}, user_role="admin")


# ── 2. BALANCED MODE ────────────────────────────────────────
print(DIVIDER)
print("  2) BALANCED MODE")
print(DIVIDER)

guard_balanced = Interceptor(mode="balanced")

print("\n→ HIGH risk → confirmation required (not blocked):")
d = guard_balanced.run("drop_table", {"table": "users"})

print("\n→ MEDIUM risk → allowed with warning:")
d = guard_balanced.run("write_file", {"path": "/etc/config.yaml"})


# ── 3. OBSERVE MODE ─────────────────────────────────────────
print(DIVIDER)
print("  3) OBSERVE MODE (never blocks)")
print(DIVIDER)

guard_observe = Interceptor(mode="observe")

print("\n→ HIGH risk but observe mode — still allowed:")
d = guard_observe.run("delete_file", {"path": "/critical/production.db"})
print(f"   allowed={d.allowed}")


# ── 4. YAML POLICY ──────────────────────────────────────────
print(DIVIDER)
print("  4) YAML POLICY OVERRIDES")
print(DIVIDER)

policy_yaml = textwrap.dedent("""\
    tools:
      deploy_to_prod:
        risk: HIGH
      lint_code:
        risk: LOW

    keywords:
      - nuke
      - purge
""")

policy_file = Path(tempfile.mktemp(suffix=".yaml"))
policy_file.write_text(policy_yaml)

guard_policy = Interceptor(mode="strict", policy_path=policy_file)

print("\n→ 'deploy_to_prod' forced HIGH by policy:")
d = guard_policy.run("deploy_to_prod", {"env": "production"})

print("\n→ 'nuke_cache' matches custom keyword:")
d = guard_policy.run("nuke_cache", {"region": "us-east-1"})

print("\n→ 'lint_code' forced LOW by policy:")
d = guard_policy.run("lint_code", {"file": "main.py"})


# ── 5. ROLE-BASED APPROVAL ──────────────────────────────────
print(DIVIDER)
print("  5) ROLE-BASED APPROVAL")
print(DIVIDER)

guard_roles = Interceptor(mode="strict")

print("\n→ user tries HIGH risk → blocked:")
d = guard_roles.run("remove_user", {"user_id": "42"}, user_role="user")

print("\n→ admin tries same → allowed:")
d = guard_roles.run("remove_user", {"user_id": "42"}, user_role="admin")

print("\n→ system role also allowed:")
d = guard_roles.run("remove_user", {"user_id": "42"}, user_role="system")


# ── 6. OVERRIDE TOKENS ──────────────────────────────────────
print(DIVIDER)
print("  6) SINGLE-USE OVERRIDE TOKEN")
print(DIVIDER)

guard_token = Interceptor(mode="strict")
token = guard_token.generate_override_token()
print(f"   Generated token: {token[:16]}...")

print("\n→ First use with token — bypasses block:")
d = guard_token.run("delete_file", {"path": "/data"}, user_role="user", override_token=token)
print(f"   allowed={d.allowed}")

print("\n→ Second use with same token — consumed, falls back to blocked:")
d = guard_token.run("delete_file", {"path": "/data"}, user_role="user", override_token=token)
print(f"   allowed={d.allowed}")


# ── 7. RETRY THROTTLING ─────────────────────────────────────
print(DIVIDER)
print("  7) RETRY THROTTLING")
print(DIVIDER)

guard_throttle = Interceptor(mode="strict", retry_limit=3, retry_window=60)

print("   Calling 'fetch_data' 4 times (limit=3)...")
for i in range(4):
    d = guard_throttle.run("fetch_data", {"page": str(i)}, user_role="admin")
    print(f"   Call {i+1}: risk={d.risk_level.value}, allowed={d.allowed}")


# ── 8. CONFIRMATION CALLBACK ────────────────────────────────
print(DIVIDER)
print("  8) CONFIRMATION CALLBACK")
print(DIVIDER)

def auto_approve(decision):
    print(f"   🔔 Callback received! Auto-approving: {decision.intent_summary}")
    return True

guard_cb = Interceptor(mode="strict", confirmation_callback=auto_approve)

print("\n→ MEDIUM risk with auto-approve callback:")
d = guard_cb.run("write_file", {"path": "/tmp/config.yaml"})
print(f"   allowed={d.allowed}")


# ── 9. @intercept DECORATOR ─────────────────────────────────
print(DIVIDER)
print("  9) @intercept DECORATOR")
print(DIVIDER)

guard_dec = Interceptor(mode="strict")

@intercept(guard_dec, user_role="admin")
def send_email(to: str = "", subject: str = ""):
    return f"📧 Email sent to {to}: {subject}"

print("\n→ Decorated function (admin, LOW risk):")
result = send_email(to="team@company.com", subject="Weekly update")
print(f"   Result: {result}")


# ── 10. VIBECODER EXPLAINER ─────────────────────────────────
print(DIVIDER)
print("  10) VIBECODER EXPLAINER")
print(DIVIDER)

guard_vibe = Interceptor(mode="strict")

print("\n→ HIGH risk — check explanation field:")
d = guard_vibe.run("delete_file", {"path": "/home/user/photos"}, user_role="user")
print(f"   explanation: {d.explanation}")

print("\n→ MEDIUM risk — check explanation field:")
d = guard_vibe.run("write_file", {"path": "/etc/nginx.conf"}, user_role="user")
print(f"   explanation: {d.explanation}")

print("\n→ LOW risk — no explanation (no noise):")
d = guard_vibe.run("read_file", {"key": "x"}, user_role="user")
print(f"   explanation: {d.explanation}")


print(DIVIDER)
print("  ✅ ALL FEATURES DEMO COMPLETE")
print(DIVIDER)
