"""Smoke test — проверяет что сервер отвечает на все основные маршруты.
Запуск: TEST_SERVER_URL=http://localhost:8000 pytest tests/test_smoke_server.py -v

Работает против запущенного сервера (локально или удалённо).
Не требует БД — просто проверяет что ответ не 404 и не 502.
"""

import os
import httpx
import pytest

SERVER_URL = os.environ.get("TEST_SERVER_URL", "http://localhost:8000")

# All GET routes from the sidebar + common pages
ROUTES_TO_CHECK = [
    "/service/dashboard",
    "/service/charts",
    "/service/ceo",
    "/service/customers",
    "/service/objects",
    "/service/sla",
    "/service/questionnaire",
    "/service/passports",
    "/service/users",
    "/service/assignments",
    "/service/tasks",
    "/service/reports",
    "/service/incidents",
    "/service/checklist",
    "/service/documents/",
    "/service/documents/tech-access",
    "/service/blog",
    "/service/cases",
    "/service/ideas",
    "/service/questionnaire-config",
    "/service/formulas",
    "/service/coefficients",
    "/service/coefficients/test",
    "/service/portal-settings",
    "/service/role-settings",
    "/service/quick-menu",
]

# API routes (should work with or without auth)
API_ROUTES = [
    "/service/api/shs",
    "/service/api/changelog",
    "/service/api/quick-menu",
]


@pytest.fixture(scope="module")
def client():
    with httpx.Client(base_url=SERVER_URL, follow_redirects=False, timeout=10) as c:
        yield c


class TestServerReachable:
    def test_health(self, client):
        resp = client.get("/health")
        assert resp.status_code == 200

    def test_login_page(self, client):
        resp = client.get("/service/login")
        assert resp.status_code == 200

    def test_root_redirect(self, client):
        resp = client.get("/")
        assert resp.status_code == 200 or resp.status_code == 302


class TestAuthPagesRedirect:
    """Without auth, should redirect to login (302) or show login page (200)."""

    @pytest.mark.parametrize("path", ROUTES_TO_CHECK)
    def test_redirect_to_login(self, client, path):
        resp = client.get(path, follow_redirects=False)
        assert resp.status_code in (200, 302, 403), \
            f"GET {path}: got {resp.status_code} (expected 302 redirect or 200/403)"


class TestApiRoutes:
    """API routes bypass auth middleware — should not 404."""

    @pytest.mark.parametrize("path", API_ROUTES)
    def test_api_not_404(self, client, path):
        resp = client.get(path)
        assert resp.status_code != 404, f"API {path} returned 404 (route missing)"
