"""Tests für den read-only LLM-/System-Status (Admin-Panel).

Getestet: GET /api/admin/llm/status — Auth-Gate + Antwortschema. Die Status-Helfer
rufen externe Tools (docker/ollama/nvidia-smi/systemctl) auf; fehlen sie in der
Testumgebung, liefern sie sichere Defaults -> der Endpunkt bleibt 200.
"""

import pytest
from fastapi.testclient import TestClient

from app.main import app
from app.config import settings

client = TestClient(app)
ADMIN = "test-admin-key"
ADM_HDR = {"X-Admin-Key": ADMIN}


@pytest.fixture(autouse=True)
def _setup(monkeypatch):
    monkeypatch.setattr(settings, "admin_api_key", ADMIN)
    monkeypatch.setattr(settings, "auth_enabled", False)
    yield


def test_status_requires_admin():
    # Ohne Admin-Key (Auth aus -> anonym, kein Admin) -> 401.
    assert client.get("/api/admin/llm/status").status_code == 401


def test_status_schema():
    resp = client.get("/api/admin/llm/status", headers=ADM_HDR)
    assert resp.status_code == 200
    data = resp.json()
    for key in ("backend", "model", "base_url", "llamacpp_running",
                "ollama_reachable", "ollama_loaded", "gpus", "gateway_service_active"):
        assert key in data, key
    assert isinstance(data["ollama_loaded"], list)
    assert isinstance(data["gpus"], list)
    # backend wird aus der base_url abgeleitet.
    assert data["backend"] in ("ollama", "llamacpp", "unknown")


# ── Schreibende Steuerung: Validierung & Auth (ohne echten Switch) ───────────

def test_backend_switch_requires_admin():
    assert client.post("/api/admin/llm/backend", json={"backend": "ollama"}).status_code == 401


def test_backend_switch_rejects_unknown_backend():
    # Ungültiges Backend -> 422, KEIN Prozess wird gestartet.
    r = client.post("/api/admin/llm/backend", json={"backend": "boese; rm -rf /"}, headers=ADM_HDR)
    assert r.status_code == 422


def test_backend_switch_rejects_bad_model(monkeypatch):
    # Modell, das nicht in 'ollama list' ist -> 422 (sofern eine Liste vorhanden ist).
    import app.admin_llm as al

    async def fake_models():
        return ["gemma3:latest", "qwen2.5:latest"]

    monkeypatch.setattr(al, "available_ollama_models", fake_models)
    r = client.post("/api/admin/llm/backend",
                    json={"backend": "ollama", "model": "gibtsnicht:99b"}, headers=ADM_HDR)
    assert r.status_code == 422


def test_backend_switch_rejects_malformed_model(monkeypatch):
    # Modellname mit Shell-Metazeichen -> 422 (Format-Regex), kein Subprozess.
    r = client.post("/api/admin/llm/backend",
                    json={"backend": "ollama", "model": "a; rm -rf /"}, headers=ADM_HDR)
    assert r.status_code == 422


def test_gateway_restart_requires_admin():
    assert client.post("/api/admin/gateway/restart").status_code == 401
