"""Smoke tests for /api/ai/vision-identify (Phase A — Smart Floating AI).

Pattern matches /app/backend/tests/test_smoke.py — uses the shared
`admin_session` fixture from conftest.py.
"""
import base64

import pytest
import requests

from conftest import BASE_URL  # type: ignore[import-not-found]


# 1×1 transparent PNG (24 bytes) — valid base64 image payload
_TINY_PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
)


@pytest.mark.critical
class TestVisionIdentify:
    def test_missing_image_data_url_returns_400(self, admin_session):
        r = admin_session.post(f"{BASE_URL}/api/ai/vision-identify", json={}, timeout=30)
        assert r.status_code == 400, r.text
        assert "image_data_url" in (r.json().get("detail") or "")

    def test_invalid_data_url_returns_400(self, admin_session):
        r = admin_session.post(
            f"{BASE_URL}/api/ai/vision-identify",
            json={"image_data_url": "not-a-data-url"},
            timeout=30,
        )
        assert r.status_code == 400, r.text

    def test_unauthenticated_callers_blocked(self):
        # Fresh session with NO cookies / no auth
        anon = requests.Session()
        anon.headers.update({"Content-Type": "application/json"})
        r = anon.post(
            f"{BASE_URL}/api/ai/vision-identify",
            json={"image_data_url": f"data:image/png;base64,{_TINY_PNG_B64}"},
            timeout=30,
        )
        assert r.status_code in (401, 403), r.text

    def test_endpoint_mounted_and_returns_schema(self, admin_session):
        """Hits the real LLM. With a 1×1 PNG it should return name=Unknown
        but the JSON shape must still be intact."""
        r = admin_session.post(
            f"{BASE_URL}/api/ai/vision-identify",
            json={"image_data_url": f"data:image/png;base64,{_TINY_PNG_B64}", "hint": "smoke test"},
            timeout=60,
        )
        # 200 (LLM responded), 502 (LLM error), 503 (no key) all indicate the route is mounted
        assert r.status_code in (200, 502, 503), r.text
        if r.status_code == 200:
            body = r.json()
            for k in ("name", "category", "purpose", "unit", "related"):
                assert k in body, f"missing key {k} in response: {body}"
