import os
import sys
from pathlib import Path

import pytest
from fastapi.testclient import TestClient

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import server  # noqa: E402


@pytest.fixture()
def client(monkeypatch):
    monkeypatch.setenv("{{SLUG}}_TOKEN", "test-token")
    return TestClient(server.app)


def test_health_is_public(client):
    r = client.get("/api/health")
    assert r.status_code == 200 and r.json()["body"] == "{{slug}}" and r.json()["auth"] is True


def test_fail_closed_without_bearer(client):
    assert client.get("/api/telemetry").status_code == 401
    assert client.post("/api/chat", json={"prompt": "hi"}).status_code == 401
    assert client.get("/api/camera/snapshot").status_code == 401


def test_endpoint_actions_with_bearer(client):
    h = {"Authorization": "Bearer test-token"}
    t = client.get("/api/telemetry", headers=h)
    assert t.status_code == 200 and t.json()["body"] == "{{slug}}"
    c = client.post("/api/chat", headers=h, json={"prompt": "status?"})
    assert c.status_code == 200 and "result" in c.json()
    assert client.post("/api/chat", headers=h, json={}).status_code == 422
    assert client.get("/api/camera/snapshot", headers=h).status_code == 503  # no frame wired yet


def test_query_token_and_cookie(client):
    assert client.get("/api/telemetry?token=test-token").status_code == 200
    r = client.get("/api/auth/login?token=test-token", follow_redirects=False)
    assert r.status_code == 303 and "{{slug}}_session" in r.cookies
