"""
intercept-ai v0.2.0 — Full Feature Demo
=========================================
Run: python demo.py
"""

from interceptor import Interceptor, intercept

print("=" * 60)
print("  intercept-ai v0.2.0 — ALL FEATURES")
print("=" * 60)


# ── 1. STRICT MODE ──────────────────────────────────────────
print("\n[1] STRICT MODE")
print("    HIGH=blocked, MEDIUM=confirm, LOW=allowed\n")

guard = Interceptor(mode="strict")

guard.run("read_config", {"key": "db_host"})
guard.run("write_file", {"path": "/app/settings.yaml", "content": "debug: true"})
guard.run("delete_file", {"path": "/data/production.db"}, user_role="user")


# ── 2. ADMIN OVERRIDE ──────────────────────────────────────
print("\n" + "-" * 60)
print("[2] ROLE-BASED APPROVAL")
print("    Same delete, but as admin\n")

guard.run("delete_file", {"path": "/data/production.db"}, user_role="admin")


# ── 3. BALANCED MODE ───────────────────────────────────────
print("\n" + "-" * 60)
print("[3] BALANCED MODE")
print("    HIGH=confirm (not block), MEDIUM=warn\n")

balanced = Interceptor(mode="balanced")
balanced.run("delete_file", {"path": "/tmp/old_cache"})
balanced.run("write_file", {"path": "/app/config.yaml", "content": "x"})


# ── 4. OBSERVE MODE ───────────────────────────────────────
print("\n" + "-" * 60)
print("[4] OBSERVE MODE")
print("    Never blocks — logs only\n")

observer = Interceptor(mode="observe")
observer.run("delete_file", {"path": "/everything"})


# ── 5. HIDDEN DANGER IN ARGUMENTS ─────────────────────────
print("\n" + "-" * 60)
print("[5] HIDDEN DANGER IN ARGUMENTS")
print("    Tool name is safe, but args contain DROP\n")

guard.run("run_query", {"sql": "DROP TABLE users; --"})


# ── 6. OVERRIDE TOKEN ────────────────────────────────────
print("\n" + "-" * 60)
print("[6] SINGLE-USE OVERRIDE TOKEN")
print("    Bypass once, then it's consumed\n")

token = guard.generate_override_token()
print(f"    Token: {token[:20]}...")
guard.run("delete_file", {"path": "/data/old_backup"}, override_token=token)
print("    Reusing same token:")
guard.run("delete_file", {"path": "/data/old_backup"}, override_token=token)


# ── 7. RETRY THROTTLING ─────────────────────────────────
print("\n" + "-" * 60)
print("[7] RETRY THROTTLING")
print("    Same tool 6x → auto-escalated to HIGH\n")

throttle_guard = Interceptor(mode="strict", retry_limit=3, retry_window=60)
for i in range(5):
    d = throttle_guard.run("call_api", {"endpoint": "/data"}, user_role="admin")
    label = "ALLOWED" if d.allowed else "ESCALATED"
    print(f"    Call {i+1}: risk={d.risk_level.value} → {label}")


# ── 8. YAML POLICY ──────────────────────────────────────
print("\n" + "-" * 60)
print("[8] YAML POLICY")
print("    Custom rules from a policy file\n")

import tempfile, os
policy_content = """
tools:
  send_invoice:
    risk: HIGH
  read_logs:
    risk: LOW

keywords:
  - purge
  - nuke
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
    f.write(policy_content)
    policy_path = f.name

policy_guard = Interceptor(mode="strict", policy_path=policy_path)
policy_guard.run("send_invoice", {"to": "client@co.com", "amount": "5000"})
policy_guard.run("nuke_cache", {"target": "all"})
os.unlink(policy_path)


# ── 9. CONFIRMATION CALLBACK ───────────────────────────
print("\n" + "-" * 60)
print("[9] CONFIRMATION CALLBACK")
print("    Auto-approve via callback function\n")

def auto_approve(decision):
    print(f"    [Callback] Auto-approving: {decision.intent_summary}")
    return True

callback_guard = Interceptor(mode="strict", confirmation_callback=auto_approve)
callback_guard.run("write_file", {"path": "/app/deploy.yaml", "content": "v2"})


# ── 10. @intercept DECORATOR ──────────────────────────
print("\n" + "-" * 60)
print("[10] @intercept DECORATOR")
print("     Wrap real functions\n")

@intercept(guard, user_role="admin")
def deploy(service: str = "", version: str = ""):
    return f"Deployed {service} v{version}"

@intercept(guard, user_role="user")
def wipe_database(confirm: str = ""):
    return "Database wiped"

result = deploy(service="api", version="3.0")
print(f"    deploy() returned: {result}")

result = wipe_database(confirm="yes")
print(f"    wipe_database() returned: {result}")


# ── 11. EXPLAINER ────────────────────────────────────
print("\n" + "-" * 60)
print("[11] PLAIN-ENGLISH EXPLAINER")
print("     .explanation field on MEDIUM/HIGH decisions\n")

d = guard.run("overwrite_config", {"path": "/etc/nginx/nginx.conf"})
print(f"    explanation: {d.explanation}")

d = guard.run("list_files", {"dir": "src"})
print(f"    explanation: {d.explanation}  (None for LOW risk)")


# ── 12. SESSION REPORT ──────────────────────────────
print("\n" + "-" * 60)
print("[12] SESSION REPORT")
print("     guard.print_report() — full session summary\n")

guard.print_report()

print("\n" + "=" * 60)
print("  DEMO COMPLETE — 12 features demonstrated")
print("=" * 60)
