"""Targeted coverage tests for rest_api.py uncovered lines.

Covers:
- L39: auth success path (valid key → call_next)
- L46-47: _parse_body except branch (malformed JSON)
- L246-247: /docs HTML endpoint
"""

from __future__ import annotations

import pytest
from starlette.testclient import TestClient

from orxaq.enterprise.auth import APIKeyStore, AuthMiddleware
from orxaq.experiences.rest_api import make_app


@pytest.fixture(scope="module")
def _open():
    return TestClient(make_app())


@pytest.fixture(scope="module")
def _authed():
    store = APIKeyStore()
    raw_key, _ = store.generate_key("cov-test")
    mw = AuthMiddleware(key_store=store)
    return TestClient(make_app(auth_middleware=mw)), raw_key


class TestRestApiCoveragePaths:
    def test_authed_success_path(self, _authed):
        """L39: auth gate dispatches authenticated request to handler."""
        client, raw_key = _authed
        r = client.get("/api/v1/ontology", headers={"X-API-Key": raw_key})
        assert r.status_code == 200
        assert "entities" in r.json()

    def test_malformed_json_body_falls_back(self, _open):
        """L46-47: _parse_body except → empty dict → defaults used."""
        r = _open.post(
            "/api/v1/ecl/compute",
            content=b"{bad json",
            headers={"Content-Type": "application/json"},
        )
        # Default portfolio_size=200 → 200 OK with ecl result
        assert r.status_code == 200
        assert "ecl" in r.json()

    def test_docs_html_endpoint(self, _open):
        """L246-247: /docs returns HTML with openapi spec."""
        r = _open.get("/docs")
        assert r.status_code == 200
        assert "text/html" in r.headers["content-type"]
        assert "openapi" in r.text.lower()
