"""Bearer auth on protected routes; healthz stays open."""


def test_healthz_open(client):
    r = client.get("/healthz")
    assert r.status_code == 200
    assert r.json() == {"ok": True}


def test_status_requires_auth(client):
    assert client.get("/v1/status").status_code == 401


def test_status_rejects_wrong_key(client):
    r = client.get("/v1/status", headers={"Authorization": "Bearer nope"})
    assert r.status_code == 401


def test_status_accepts_valid_key(client, auth_headers):
    r = client.get("/v1/status", headers=auth_headers)
    assert r.status_code == 200
    body = r.json()
    assert body["server_version"] == "1.0.0"
    assert body["ready"] is True
    assert body["gpu"]["cuda"] is True


def test_missing_scheme_rejected(client):
    r = client.get("/v1/status", headers={"Authorization": "testkey"})
    assert r.status_code == 401


def test_request_id_echoed(client, auth_headers):
    r = client.get("/v1/status", headers={**auth_headers, "x-request-id": "abc123"})
    assert r.headers.get("x-request-id") == "abc123"


def test_empty_key_is_autogenerated(tmp_path, monkeypatch):
    """First run with no configured key generates one (server never runs
    unauthenticated) and persists it to server.toml."""
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from app import auth as auth_mod
    cfg_path = tmp_path / "server.toml"
    from app.config import ServerConfig
    cfg = ServerConfig(api_key="", host="127.0.0.1")
    key = auth_mod.ensure_api_key(cfg, cfg_path)
    assert key.startswith("vxc_") and len(key) > 10
    assert cfg_path.exists()
    assert key in cfg_path.read_text(encoding="utf-8")
