#!/usr/bin/env python3
"""Microbenchmark for the non-production authority policy evaluator."""
from __future__ import annotations
import json
import platform
import statistics
import time
from pathlib import Path

from authority_gate import ActionIntent, AuthorityGate, AuthorityGrant

NOW = 1_800_000_000
grant = AuthorityGrant(
    grant_id="grant-bench", tenant_id="tenant-bench", principal_id="agent-bench",
    task_id="task-bench", audience="darkoza-tool-gateway",
    issued_at=NOW - 1, expires_at=NOW + 300,
    tools=("calendar.read",), capabilities=("calendar.read",),
    actions=("read",), resources=("calendar:bench",),
)
intent = ActionIntent(
    intent_id="intent-bench", tenant_id="tenant-bench", principal_id="agent-bench",
    task_id="task-bench", audience="darkoza-tool-gateway",
    tool_id="calendar.read", effect_digest="a" * 64,
    capability="calendar.read", action="read", resource_id="calendar:bench",
)
gate = AuthorityGate()

for _ in range(1000):
    gate.evaluate(grant, intent, now=NOW)

latencies_ns: list[int] = []
rounds = 10
iterations = 5000
for _ in range(rounds):
    for _ in range(iterations):
        start = time.perf_counter_ns()
        result = gate.evaluate(grant, intent, now=NOW)
        latencies_ns.append(time.perf_counter_ns() - start)
        if result["decision"] != "allow":
            raise RuntimeError("benchmark request unexpectedly denied")

ordered = sorted(latencies_ns)
def percentile(p: float) -> float:
    index = min(len(ordered) - 1, int((len(ordered) - 1) * p))
    return ordered[index] / 1_000.0

payload = {
    "benchmark": "darkoza-authority-gate-local-read-policy",
    "policy_version": "darkoza-intent-authority-v0.2",
    "environment": {
        "python": platform.python_version(),
        "platform": platform.platform(),
        "processor": platform.processor(),
    },
    "warmup": 1000,
    "iterations": len(latencies_ns),
    "operations": "evaluate scoped, in-memory read grants and generate integrity receipt; no executor, network, persistence, or signature verification",
    "latency_microseconds": {
        "median": statistics.median(latencies_ns) / 1000.0,
        "p95": percentile(0.95),
        "p99": percentile(0.99),
        "min": min(latencies_ns) / 1000.0,
        "max": max(latencies_ns) / 1000.0,
    },
    "status": "local microbenchmark only; not production capacity or end-to-end latency",
}
print(json.dumps(payload, indent=2))
