import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch, AsyncMock
from main import app
from app.routers.router_auth import get_current_user_from_token, get_optional_user
from app.models.auth import User
from app.database import get_session
from sqlmodel import Session, SQLModel

# Mock user for bypassing auth
MOCK_USER = User(
    id="test-user-id",
    username="testuser",
    email="test@example.com",
    is_active=True,
    created_at="2024-01-01T00:00:00",
    last_login=None,
)


@pytest.fixture(autouse=True)
def override_deps(engine):
    """Override auth and session dependencies for all tests in this module."""
    # Ensure tables exist in the in-memory DB
    SQLModel.metadata.create_all(engine)

    # Override auth dependencies
    app.dependency_overrides[get_current_user_from_token] = lambda: MOCK_USER
    app.dependency_overrides[get_optional_user] = lambda: MOCK_USER
    # Override get_session to use the test engine with fresh tables
    def get_test_session():
        session = Session(engine)
        try:
            yield session
        finally:
            session.close()
    app.dependency_overrides[get_session] = get_test_session
    yield
    app.dependency_overrides.clear()


@pytest.fixture
def client():
    """Create TestClient that uses the context manager to handle lifespan."""
    with TestClient(app) as c:
        yield c


def test_anime_search_htmx(client):
    """Vérifie que la recherche d'anime renvoie du HTML avec HTMX"""
    response = client.get("/api/anime/search?q=Naruto", headers={"HX-Request": "true"})
    assert response.status_code == 200
    # DaisyUI template uses card bg-base-200 for result cards
    assert "card" in response.text


def test_series_search_htmx(client):
    """Vérifie que la recherche de séries renvoie du HTML avec HTMX"""
    response = client.get("/api/series/search?q=Breaking", headers={"HX-Request": "true"})
    assert response.status_code == 200
    # DaisyUI template uses card bg-base-200 for result cards
    assert "card" in response.text


def test_recommendations_htmx(client):
    """Vérifie que les recommandations renvoient du HTML"""
    response = client.get("/api/recommendations", headers={"HX-Request": "true"})
    assert response.status_code == 200
    # DaisyUI template uses card card-compact bg-base-200 for recommendation cards
    assert "card" in response.text


def test_latest_releases_htmx(client):
    """Vérifie que les sorties récentes renvoient du HTML"""
    response = client.get("/api/releases/latest", headers={"HX-Request": "true"})
    assert response.status_code == 200
    # DaisyUI template uses card card-compact bg-base-200 for release cards
    assert "card" in response.text


def test_episode_list_htmx(client):
    """Vérifie que la liste des épisodes renvoie du HTML"""
    # Utilisation d'un lien bidon pour tester le rendu du composant
    test_url = "https://anime-sama.fr/anime/vostfr/naruto"
    response = client.get(f"/api/anime/episodes?url={test_url}", headers={"HX-Request": "true"})
    assert response.status_code == 200
    # DaisyUI template uses card bg-base-200 instead of episode-list-container
    assert "card bg-base-200" in response.text
