"""Deterministic evidence backend for tests and the public control-plane demo.

This backend proves request isolation, card routing, receipts, limits, and
batching. It deliberately does not pretend to be a language model.
"""

from __future__ import annotations

import asyncio
import re
import time

from ..contracts import BackendCapabilities
from .base import Backend, BackendInput, BackendResult


class EvidenceBackend(Backend):
    def __init__(self, model: str = "control-plane-sandbox"):
        self._capabilities = BackendCapabilities(
            backend="evidence",
            model=model,
            batching=True,
            kv_cache=False,
            activation_cards=False,
            per_request_adapters=False,
            metrics=("latency_ms", "batch_size", "token_estimate"),
            limitations=(
                "Deterministic control-plane backend; no neural inference.",
                "Use TransformersBackend or VLLMBackend for model execution.",
            ),
        )

    @property
    def capabilities(self) -> BackendCapabilities:
        return self._capabilities

    async def generate_batch(self, requests: list[BackendInput]) -> list[BackendResult]:
        started = time.perf_counter()
        await asyncio.sleep(0)
        results: list[BackendResult] = []
        for request in requests:
            prompt = request.prompt
            memory = _section(prompt, "verified tenant memory")
            sensor = _section(prompt, "signed sensor frame")
            clean = re.sub(r"\[[^\]]+\].*?\[/[^\]]+\]\s*", "", prompt, flags=re.S)
            if "refund" in clean.casefold() and memory:
                text = f"Tenant memory applied: {memory.splitlines()[0]}."
            elif sensor:
                first = sensor.splitlines()[0]
                text = f"Signed telemetry received: {first}. No cross-tenant state was read."
            elif "isolation" in clean.casefold():
                text = (
                    f"Tenant {request.tenant_id} executed stack {request.stack_key[:12]}; "
                    "state remained inside its namespace."
                )
            else:
                text = (
                    f"Backplane accepted the request for tenant {request.tenant_id}. "
                    "The declared card stack completed under its runtime budget."
                )
            elapsed = (time.perf_counter() - started) * 1000
            results.append(
                BackendResult(
                    text=text,
                    input_tokens=max(1, len(prompt.split())),
                    output_tokens=max(1, len(text.split())),
                    latency_ms=round(elapsed, 3),
                    metadata={"sandbox": True, "batch_size": len(requests)},
                )
            )
        return results


def _section(text: str, name: str) -> str:
    match = re.search(
        rf"\[{re.escape(name)}\]\n(.*?)\n\[/{re.escape(name)}\]",
        text,
        flags=re.S,
    )
    return match.group(1).strip() if match else ""

