"""Frontend tests for the edit metadata modal HTML structure."""
from unittest.mock import AsyncMock, Mock, patch

import pytest
from httpx import ASGITransport, AsyncClient

from src.server.fastapi_app import app
from src.server.services.auth_service import auth_service


@pytest.fixture(autouse=True)
def reset_auth():
    """Reset authentication state before each test."""
    original_hash = auth_service._hash
    auth_service._hash = None
    auth_service._failed.clear()
    yield
    auth_service._hash = original_hash
    auth_service._failed.clear()


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


@pytest.fixture
async def authenticated_client(client):
    """Create authenticated client to access index page."""
    await client.post(
        "/api/auth/setup",
        json={"master_password": "TestPassword123!"}
    )
    response = await client.post(
        "/api/auth/login",
        json={"password": "TestPassword123!"}
    )
    token = response.json()["access_token"]
    client.headers.update({"Authorization": f"Bearer {token}"})
    # Set cookie for page access
    client.cookies.set("access_token", token)
    yield client


class TestEditModalHtmlPresence:
    """Tests verifying edit modal HTML elements exist in index page."""

    @pytest.mark.asyncio
    async def test_index_page_contains_edit_modal(self, authenticated_client):
        """Verify #edit-metadata-modal exists in rendered index page."""
        response = await authenticated_client.get("/")

        # Page may redirect or require different auth for HTML pages
        if response.status_code == 200:
            html = response.text
            assert 'id="edit-metadata-modal"' in html

    @pytest.mark.asyncio
    async def test_index_page_loads_context_menu_script(self, authenticated_client):
        """Verify context-menu.js script tag is present."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert "context-menu.js" in html

    @pytest.mark.asyncio
    async def test_index_page_loads_edit_modal_script(self, authenticated_client):
        """Verify edit-modal.js script tag is present."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert "edit-modal.js" in html

    @pytest.mark.asyncio
    async def test_modal_form_fields_present(self, authenticated_client):
        """Verify key, tmdb_id, tvdb_id input fields exist in modal."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert 'id="edit-key"' in html
            assert 'id="edit-tmdb-id"' in html
            assert 'id="edit-tvdb-id"' in html

    @pytest.mark.asyncio
    async def test_nfo_repair_button_present(self, authenticated_client):
        """Verify repair NFO button exists in modal."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert 'id="btn-repair-nfo"' in html

    @pytest.mark.asyncio
    async def test_save_button_present(self, authenticated_client):
        """Verify save button exists in modal."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert 'id="btn-save-metadata"' in html

    @pytest.mark.asyncio
    async def test_modal_starts_hidden(self, authenticated_client):
        """Verify modal has hidden class by default."""
        response = await authenticated_client.get("/")

        if response.status_code == 200:
            html = response.text
            assert 'id="edit-metadata-modal" class="modal hidden"' in html
