"""
Tests for template integration and rendering.

This module tests that all HTML templates are properly integrated with FastAPI
and can be rendered correctly.
"""
import pytest
from httpx import ASGITransport, AsyncClient

from src.server.fastapi_app import app


class TestTemplateIntegration:
    """Test template integration with FastAPI."""

    @pytest.fixture
    async def client(self):
        """Create test client."""
        transport = ASGITransport(app=app)
        async with AsyncClient(
            transport=transport,
            base_url="http://test",
            follow_redirects=True,
        ) as ac:
            yield ac

    async def test_index_template_renders(self, client):
        """Test that index.html renders successfully."""
        response = await client.get("/")
        assert response.status_code == 200
        assert response.headers["content-type"].startswith("text/html")
        assert b"AniWorld Manager" in response.content
        assert b"/static/css/styles.css" in response.content

    async def test_login_template_renders(self, client):
        """Test that login.html renders successfully."""
        response = await client.get("/login")
        assert response.status_code == 200
        assert response.headers["content-type"].startswith("text/html")
        assert b"Login" in response.content
        assert b"/static/css/styles.css" in response.content

    async def test_setup_template_renders(self, client):
        """Test that setup.html renders successfully.
        
        Note: The /setup page may redirect to /login when auth is configured.
        We accept either the setup page or the login page.
        """
        response = await client.get("/setup")
        assert response.status_code == 200
        assert response.headers["content-type"].startswith("text/html")
        # May render setup or redirect to login
        assert b"Setup" in response.content or b"Login" in response.content
        assert b"/static/css/styles.css" in response.content

    async def test_queue_template_renders(self, client):
        """Test that queue.html renders successfully."""
        response = await client.get("/queue")
        assert response.status_code == 200
        assert response.headers["content-type"].startswith("text/html")
        assert b"Download Queue" in response.content
        assert b"/static/css/styles.css" in response.content

    async def test_error_template_404(self, client):
        """Test that 404 error page renders correctly."""
        response = await client.get("/nonexistent-page")
        # The app returns 200 with index.html for non-existent pages (SPA behavior)
        # This is expected for client-side routing
        assert response.status_code == 200
        assert response.headers["content-type"].startswith("text/html")

    async def test_static_css_accessible(self, client):
        """Test that static CSS files are accessible."""
        response = await client.get("/static/css/styles.css")
        assert response.status_code == 200
        assert "text/css" in response.headers.get("content-type", "")

    async def test_static_js_accessible(self, client):
        """Test that static JavaScript files are accessible."""
        response = await client.get("/static/js/app.js")
        assert response.status_code == 200

    async def test_templates_include_theme_switching(self, client):
        """Test that templates include theme switching functionality."""
        response = await client.get("/")
        assert response.status_code == 200
        # Check for theme toggle button
        assert b"theme-toggle" in response.content
        # Check for data-theme attribute
        assert b'data-theme="light"' in response.content

    async def test_templates_include_responsive_meta(self, client):
        """Test that templates include responsive viewport meta tag."""
        response = await client.get("/")
        assert response.status_code == 200
        assert b'name="viewport"' in response.content
        assert b"width=device-width" in response.content

    async def test_templates_include_font_awesome(self, client):
        """Test that templates include Font Awesome icons."""
        response = await client.get("/")
        assert response.status_code == 200
        assert b"font-awesome" in response.content.lower()

    async def test_all_templates_have_correct_structure(self, client):
        """Test that all templates have correct HTML structure."""
        pages = ["/", "/login", "/setup", "/queue"]
        
        for page in pages:
            response = await client.get(page)
            assert response.status_code == 200
            content = response.content
            
            # Check for essential HTML elements
            assert b"<!DOCTYPE html>" in content
            assert b"<html" in content
            assert b"<head>" in content
            assert b"<body>" in content
            assert b"</html>" in content

    async def test_templates_load_required_javascript(self, client):
        """Test that index template loads all required JavaScript modules."""
        response = await client.get("/")
        assert response.status_code == 200
        content = response.content
        
        # Check for modular JS structure (shared modules)
        assert b"/static/js/shared/constants.js" in content
        assert b"/static/js/shared/auth.js" in content
        assert b"/static/js/shared/api-client.js" in content
        
        # Check for index-specific modules
        assert b"/static/js/index/app-init.js" in content
        
        # Check for localization.js
        assert b"/static/js/localization.js" in content

    async def test_templates_load_ux_features_css(self, client):
        """Test that templates load UX features CSS."""
        response = await client.get("/")
        assert response.status_code == 200
        assert b"/static/css/ux_features.css" in response.content

    async def test_queue_template_has_websocket_script(self, client):
        """Test that queue template includes WebSocket support."""
        response = await client.get("/queue")
        assert response.status_code == 200
        # Check for modular websocket client
        assert b"/static/js/shared/websocket-client.js" in response.content

    async def test_index_includes_search_functionality(self, client):
        """Test that index page includes search functionality."""
        response = await client.get("/")
        assert response.status_code == 200
        content = response.content
        
        assert b"search-input" in content
        assert b"search-btn" in content

    async def test_templates_accessibility_features(self, client):
        """Test that templates include accessibility features."""
        response = await client.get("/")
        assert response.status_code == 200
        content = response.content
        
        # Check for accessibility scripts that are loaded
        assert (
            b"accessibility_features.js" in content or
            b"screen_reader_support.js" in content or
            b"title=" in content  # Title attributes provide accessibility
        )
