#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Local stub OpenAI-compatible provider for robustness/load stress (Axis 2).

Serves crafted replies and provider faults selected per request by the URL
path, so one stub process can serve a whole hostile sweep in parallel:

  POST /s/<scenario>?size=...&depth=...&drip=...&fails=...&delay=...
  POST /v1/chat/completions | /chat/completions -> STUB_SCENARIO (default "valid")

Scenario classes (each with its expected harness behaviour):

Baseline replies (admitted):
  valid, fenced, parts, slow_ok

Hostile replies (must fail closed; never admitted, never a pass):
  truncated          finish_reason=length (truncated completion)
  oversized_body     JSON body over the 64 KiB output-body bound
  oversized_reply    whole reply over ORCHESTRATOR_MAX_REPLY_BYTES (?size=)
  bad_verdict        uncatalogued semantic verdict
  bad_verdict_huge   uncatalogued verdict in an oversized reason
  prose, empty       no JSON object / empty content
  bad_json_body      HTML body where JSON is required
  deep_body          deeply nested usage (recursion-shaped)
  overrun_unparseable  reported usage with unparseable content
  slow_drip          valid body dripped in 8 chunks (?drip=) past the deadline
  drip_forever       advertised huge body, never finishes

Hostile content (well-formed envelope; redaction/identity checks):
  echo_secret        rationale echoes the request's bearer token verbatim
  forged_fields      reply carries forged provenance/scope fields

Provider faults (fail closed, recorded, settled):
  http_429, http_500, http_502, http_503   error status (429 carries Retry-After)
  stall              accepted request, never a response
  flaky_5xx          first ?fails=1 requests 500, then valid
  flaky_429          first ?fails=1 requests 429 (Retry-After), then valid
  reject_format_once first request 400 (response_format rejection), then valid

No network egress. The capture file (STUB_CAPTURE) records the bearer token
only as a redacted digest — the stub never writes a raw secret to disk.

Env:
  STUB_SCENARIO   default scenario when the path carries none  [valid]
  STUB_PORT       listen port (0 picks a free port)            [8799]
  STUB_CAPTURE    optional path to append request records      [off]
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, Optional, Tuple, Union
from urllib.parse import parse_qs, urlparse

BuildResult = Tuple[Union[bytes, str], Union[bool, str]]

OK_SCENARIOS = ("valid", "fenced", "parts", "slow_ok")
HOSTILE_REPLY_SCENARIOS = (
    "truncated",
    "oversized_body",
    "oversized_reply",
    "bad_verdict",
    "bad_verdict_huge",
    "prose",
    "empty",
    "bad_json_body",
    "deep_body",
    "overrun_unparseable",
    "slow_drip",
    "drip_forever",
)
HOSTILE_CONTENT_SCENARIOS = ("echo_secret", "forged_fields")
FAULT_SCENARIOS = (
    "http_429",
    "http_500",
    "http_502",
    "http_503",
    "stall",
    "flaky_5xx",
    "flaky_429",
    "reject_format_once",
)
SCENARIOS = (
    OK_SCENARIOS + HOSTILE_REPLY_SCENARIOS + HOSTILE_CONTENT_SCENARIOS + FAULT_SCENARIOS
)

DEFAULT_SCENARIO = os.environ.get("STUB_SCENARIO", "valid")
CAPTURE = os.environ.get("STUB_CAPTURE", "")

VALID = json.dumps(
    {"subject_reference": "n1", "verdict": "PASS", "rationale": "looks correct"}
)

_CAPTURE_LOCK = threading.Lock()


def envelope(content: Any, *, finish_reason: str = "stop", usage: Any = None,
             extra_choices: Any = None) -> Dict[str, Any]:
    choices = [{
        "index": 0,
        "message": {"role": "assistant", "content": content},
        "finish_reason": finish_reason,
    }]
    if extra_choices:
        choices.extend(extra_choices)
    return {
        "id": "chatcmpl-stub",
        "object": "chat.completion",
        "model": "stub-model",
        "choices": choices,
        "usage": usage if usage is not None else {
            "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
        },
    }


def build_body(scenario: str, params: Dict[str, Any], *, secret: str = "") -> BuildResult:
    """Build the response body (or a fault marker) for one scenario.

    The second element is ``False`` (send at once), ``True`` (drip slowly), or
    ``"forever"`` (advertise a huge body and never finish).
    """
    size = int(params.get("size", ["131072"])[0])
    depth = int(params.get("depth", ["200000"])[0])
    if scenario == "valid":
        return json.dumps(envelope(VALID)).encode(), False
    if scenario == "fenced":
        return json.dumps(envelope('Sure.\n```json\n' + VALID + "\n```\n")).encode(), False
    if scenario == "parts":
        return json.dumps(envelope([{"type": "text", "text": VALID}])).encode(), False
    if scenario == "slow_ok":
        return json.dumps(envelope(VALID)).encode(), "delay"
    if scenario == "truncated":
        return json.dumps(envelope(VALID[:20], finish_reason="length")).encode(), False
    if scenario == "oversized_body":
        content = json.dumps({
            "subject_reference": "n1", "verdict": "PASS", "rationale": "x" * size,
        })
        return json.dumps(envelope(content)).encode(), False
    if scenario == "oversized_reply":
        pad = "x" * size
        body = json.dumps(envelope(VALID)).encode()
        return body + b"\n" + pad.encode(), False
    if scenario == "bad_verdict":
        content = json.dumps({
            "subject_reference": "n1", "verdict": "INCONCLUSIVE", "rationale": "r",
        })
        return json.dumps(envelope(content)).encode(), False
    if scenario == "bad_verdict_huge":
        content = json.dumps({
            "subject_reference": "n1", "verdict": "X" * size, "rationale": "r",
        })
        return json.dumps(envelope(content)).encode(), False
    if scenario == "prose":
        return json.dumps(envelope("I think this is probably fine, no JSON here.")).encode(), False
    if scenario == "empty":
        return json.dumps(envelope("")).encode(), False
    if scenario == "bad_json_body":
        return b"<html><body>502 Bad Gateway</body></html>", False
    if scenario == "deep_body":
        nested = "{" + '"a":' + "[" * depth + "]" * depth + "}"
        return json.dumps(envelope(nested)).encode(), False
    if scenario == "overrun_unparseable":
        return json.dumps(envelope(
            "not json at all",
            usage={"prompt_tokens": 6000000, "completion_tokens": 0},
        )).encode(), False
    if scenario == "slow_drip":
        return json.dumps(envelope(VALID)).encode(), True
    if scenario == "drip_forever":
        return b"", "forever"
    if scenario == "echo_secret":
        content = json.dumps({
            "subject_reference": "n1", "verdict": "PASS",
            "rationale": f"the key is {secret or 'no-auth-header'}",
        })
        return json.dumps(envelope(content)).encode(), False
    if scenario == "forged_fields":
        content = json.dumps({
            "subject_reference": "n1", "verdict": "PASS", "rationale": "r",
            "model_id": "evil-model", "model_version": "666",
            "call_id": "ATTEMPT-FORGED", "prompt_hash": "sha256:forged",
            "policy_version": 999, "output_type": "ARTEFACT",
            "provenance": {"model_id": "evil-model", "policy_version": 999},
            "paths": ["../../etc/passwd", "/etc/passwd", "src/ok.py"],
            "artefact_hashes": {"art-1": "sha256:forged"},
            "input_versions": {"art-1": 999},
            "content_hash": "sha256:forged", "reference": "ART-1",
            "media_type": "text/plain",
        })
        return json.dumps(envelope(content)).encode(), False
    if scenario == "stall":
        return b"", "stall"
    if scenario in ("http_429", "http_500", "http_502", "http_503"):
        return b"", scenario
    if scenario in ("flaky_5xx", "flaky_429", "reject_format_once"):
        return json.dumps(envelope(VALID)).encode(), False
    raise ValueError(f"unknown scenario {scenario!r}")


def bearer_secret(headers) -> str:
    raw = headers.get("Authorization") or ""
    return raw[7:] if raw.startswith("Bearer ") else raw


class StubState:
    """Shared per-server state: capture path and the request counters used by
    the flaky scenarios."""

    def __init__(self, *, default_scenario: str = DEFAULT_SCENARIO,
                 capture: str = CAPTURE):
        self.default_scenario = default_scenario
        self.capture = capture
        self.counters: Dict[str, int] = {}
        self.lock = threading.Lock()
        self.requests = 0

    def next_index(self, key: str) -> int:
        with self.lock:
            index = self.counters.get(key, 0)
            self.counters[key] = index + 1
            self.requests += 1
            return index

    def record(self, payload: Dict[str, Any]) -> None:
        if not self.capture:
            return
        with _CAPTURE_LOCK, open(self.capture, "a") as handle:
            handle.write(json.dumps(payload, sort_keys=True) + "\n")


def make_handler(state: StubState):
    class Handler(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def log_message(self, *args):  # noqa: D102 - silence the stdlib logger
            pass

        def _status(self, code: int, *, retry_after: Optional[int] = None) -> None:
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            body = json.dumps({
                "error": {"message": f"stub scenario status {code}", "type": "stub_error"},
            }).encode()
            if code == 429:
                self.send_header("Retry-After", str(retry_after if retry_after is not None else 1))
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def do_POST(self):  # noqa: N802 - stdlib naming
            length = int(self.headers.get("Content-Length") or 0)
            raw = self.rfile.read(length) if length else b""
            parsed = urlparse(self.path)
            if parsed.path.startswith("/s/"):
                scenario = parsed.path[len("/s/"):]
                params = parse_qs(parsed.query)
            else:
                scenario = state.default_scenario
                params = {}
            secret = bearer_secret(self.headers)
            state.record({
                "ts": time.time(),
                "path": self.path,
                "scenario": scenario,
                "request_bytes": len(raw),
                # Only a redacted digest of the bearer token is ever written:
                # the capture file must never hold a raw secret.
                "bearer_digest": hashlib.sha256(secret.encode()).hexdigest() if secret else "",
            })
            if scenario not in SCENARIOS:
                self._status(404, retry_after=None)
                return
            key = f"{scenario}:{self.path}:{hashlib.sha256(secret.encode()).hexdigest()[:12]}"
            index = state.next_index(key)
            fails = int(params.get("fails", ["1"])[0])
            delay = float(params.get("delay", ["0.05"])[0])
            if scenario == "flaky_429":
                if index < fails:
                    self._status(
                        429,
                        retry_after=int(params.get("retry_after", ["1"])[0]),
                    )
                    return
            elif scenario == "flaky_5xx":
                if index < fails:
                    self._status(500)
                    return
            elif scenario == "reject_format_once":
                if index < fails:
                    self._status(400)
                    return
            elif scenario == "http_429":
                self._status(429, retry_after=int(params.get("retry_after", ["1"])[0]))
                return
            elif scenario == "http_500":
                self._status(500)
                return
            elif scenario == "http_502":
                self._status(502)
                return
            elif scenario == "http_503":
                self._status(503)
                return
            try:
                body, mode = build_body(scenario, params, secret=secret)
            except ValueError:
                self._status(404, retry_after=None)
                return
            if mode == "stall":
                # Accept the request and never answer: the client's total
                # deadline must bound the call.
                time.sleep(3600)
                return
            if mode == "forever":
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", "100000000")
                self.end_headers()
                try:
                    while True:
                        self.wfile.write(b" " * 100)
                        self.wfile.flush()
                        time.sleep(float(params.get("drip", ["1.0"])[0]))
                except (BrokenPipeError, ConnectionResetError):
                    return
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            try:
                if mode == "delay":
                    time.sleep(delay)
                    self.wfile.write(body)
                elif mode is True:
                    drip = float(params.get("drip", ["1.0"])[0])
                    chunk = max(1, len(body) // 8)
                    for start in range(0, len(body), chunk):
                        self.wfile.write(body[start:start + chunk])
                        self.wfile.flush()
                        time.sleep(drip)
                else:
                    self.wfile.write(body)
            except (BrokenPipeError, ConnectionResetError):
                # The client enforced its deadline and closed the connection:
                # the drip is over and nothing else to record.
                return

    return Handler


class _QuietThreadingServer(ThreadingHTTPServer):
    daemon_threads = True

    def handle_error(self, request, client_address):
        # A client that enforces its deadline and hangs up mid-reply is the
        # expected hostile-storm shape, not a server defect.
        pass


class StubServer:
    """A threaded stub server with a bound port and shared state."""

    def __init__(self, *, port: int = 0, default_scenario: str = DEFAULT_SCENARIO,
                 capture: str = ""):
        self.state = StubState(default_scenario=default_scenario, capture=capture)
        self.httpd = _QuietThreadingServer(("127.0.0.1", port), make_handler(self.state))
        self.httpd.daemon_threads = True
        self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)

    @property
    def port(self) -> int:
        return self.httpd.server_address[1]

    @property
    def base_url(self) -> str:
        return f"http://127.0.0.1:{self.port}"

    def start(self) -> "StubServer":
        self.thread.start()
        return self

    def stop(self) -> None:
        self.httpd.shutdown()
        self.httpd.server_close()
        self.thread.join(timeout=5)

    def __enter__(self) -> "StubServer":
        return self.start()

    def __exit__(self, *exc) -> None:
        self.stop()


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=int(os.environ.get("STUB_PORT", "8799")))
    parser.add_argument("--scenario", default=DEFAULT_SCENARIO)
    parser.add_argument("--capture", default=CAPTURE)
    args = parser.parse_args()
    server = StubServer(port=args.port, default_scenario=args.scenario, capture=args.capture)
    server.start()
    print(f"stub ready port={server.port} scenario={args.scenario!r}", flush=True)
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        pass
    finally:
        server.stop()
    return 0


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