"""Run with Python 3.12 and redis-server on PATH.

Install the tested Python packages in a virtual environment:
    python -m pip install 'litellm[proxy]==1.111.1' redis

This demonstration starts its own Redis instance and a counting HTTP endpoint
on loopback. No provider account or API key is required.
"""

import json
import os
import shutil
import socket
import subprocess
import tempfile
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version
from pathlib import Path
from threading import Thread

os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
os.environ["LITELLM_TELEMETRY"] = "False"

import litellm
import redis
from litellm.caching.caching import Cache


class CountingProvider(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/v1/chat/completions":
            self.send_error(404)
            return
        request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        self.server.calls += 1
        response = {
            "id": f"local-response-{self.server.calls}",
            "object": "chat.completion",
            "created": int(time.time()),
            "model": request["model"],
            "choices": [
                {
                    "index": 0,
                    "message": {"role": "assistant", "content": "OK"},
                    "finish_reason": "stop",
                }
            ],
            "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
        }
        data = json.dumps(response).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *_):
        pass


def run():
    with socket.socket() as probe:
        probe.bind(("127.0.0.1", 0))
        port = probe.getsockname()[1]
    with (
        tempfile.TemporaryDirectory() as scratch,
        ThreadingHTTPServer(("127.0.0.1", 0), CountingProvider) as provider,
    ):
        executable = shutil.which("redis-server")
        if not executable:
            raise RuntimeError("Install redis-server and add it to PATH.")
        process = subprocess.Popen(
            [
                executable,
                "--bind",
                "127.0.0.1",
                "--port",
                str(port),
                "--dir",
                str(Path(scratch)),
                "--save",
                "",
                "--appendonly",
                "no",
            ],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.STDOUT,
        )
        provider.calls = 0
        Thread(target=provider.serve_forever, daemon=True).start()
        try:
            client = redis.Redis(host="127.0.0.1", port=port)
            for _ in range(100):
                if process.poll() is not None:
                    raise RuntimeError("Private Redis failed to start.")
                try:
                    if (
                        client.ping()
                        and int(client.info("server")["process_id"]) == process.pid
                    ):
                        break
                except redis.ConnectionError:
                    pass
                time.sleep(0.05)
            else:
                raise RuntimeError("Could not reach the private Redis process.")
            litellm.cache = Cache(type="redis", host="127.0.0.1", port=port, ttl=300)
            observations = []
            for name, prompt in [("cold", "A"), ("repeat", "A"), ("changed", "B")]:
                reply = litellm.completion(
                    model="openai/gpt-4o-mini",
                    temperature=0,
                    api_base=f"http://127.0.0.1:{provider.server_port}/v1",
                    api_key="local-only",
                    messages=[{"role": "user", "content": prompt}],
                )
                observations.append(
                    {
                        "request": name,
                        "response_id": reply.id,
                        "upstream_calls_so_far": provider.calls,
                        "redis_keys": client.dbsize(),
                    }
                )
            if [r["upstream_calls_so_far"] for r in observations] != [1, 1, 2]:
                raise AssertionError(observations)
            if [r["redis_keys"] for r in observations] != [1, 1, 2]:
                raise AssertionError(observations)
            if observations[0]["response_id"] != observations[1]["response_id"]:
                raise AssertionError(observations)
            return {
                "litellm": version("litellm"),
                "redis_server": client.info("server")["redis_version"],
                "provider": "loopback counting fixture",
                "model_requests_to_paid_services": 0,
                "observations": observations,
            }
        finally:
            litellm.cache = None
            provider.shutdown()
            process.terminate()
            process.wait(timeout=5)


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
