"""
Tests for Issue #1 (Audit Logging Integration) and Issue #2 (ResultManager in API).

These tests verify the fixes for:
1. AuditMiddleware is exported and added to the API app
2. ResultManager.store_result() is called in the API fallback path
"""


import pytest


class TestAuditLoggingExports:
    """Test that audit logging is properly exported from backend module."""

    def test_audit_logger_exported(self):
        """Test AuditLogger is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditLogger
        assert AuditLogger is not None

    def test_audit_middleware_exported(self):
        """Test AuditMiddleware is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditMiddleware
        assert AuditMiddleware is not None

    def test_audit_event_type_exported(self):
        """Test AuditEventType is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditEventType
        assert AuditEventType is not None

    def test_audit_severity_exported(self):
        """Test AuditSeverity is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditSeverity
        assert AuditSeverity is not None

    def test_audit_outcome_exported(self):
        """Test AuditOutcome is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditOutcome
        assert AuditOutcome is not None

    def test_audit_event_exported(self):
        """Test AuditEvent is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import AuditEvent
        assert AuditEvent is not None

    def test_get_audit_logger_exported(self):
        """Test get_audit_logger is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import get_audit_logger
        assert get_audit_logger is not None
        assert callable(get_audit_logger)

    def test_create_audit_logger_exported(self):
        """Test create_audit_logger is exported from verlex_server.gateway.backend."""
        from verlex_server.gateway.backend import create_audit_logger
        assert create_audit_logger is not None
        assert callable(create_audit_logger)

    def test_get_audit_logger_returns_singleton(self):
        """Test get_audit_logger returns the same instance."""
        from verlex_server.gateway.backend import AuditLogger, get_audit_logger

        logger1 = get_audit_logger()
        logger2 = get_audit_logger()

        assert logger1 is logger2
        assert isinstance(logger1, AuditLogger)


class TestAuditMiddlewareInAPI:
    """Test that AuditMiddleware is added to the FastAPI app."""

    def test_api_creates_successfully_with_audit_middleware(self):
        """Test that create_app() works with AuditMiddleware."""
        from verlex_server.gateway.backend.api import create_app

        app = create_app()
        assert app is not None

    def test_audit_middleware_in_app_stack(self):
        """Test that AuditMiddleware is in the middleware stack."""
        from verlex_server.gateway.backend.api import create_app

        app = create_app()

        # Check if any middleware contains 'Audit' in its representation
        middleware_found = False
        for m in app.user_middleware:
            middleware_repr = str(m)
            if 'Audit' in middleware_repr or 'audit' in middleware_repr.lower():
                middleware_found = True
                break

        assert middleware_found, "AuditMiddleware should be in app middleware stack"


class TestResultManagerIntegration:
    """Test ResultManager integration in API module."""

    def test_result_manager_importable(self):
        """Test ResultManager can be imported from core.results."""
        from verlex_server.gateway.core.results import ResultManager, get_result_manager

        rm = get_result_manager()
        assert isinstance(rm, ResultManager)

    def test_result_manager_singleton(self):
        """Test get_result_manager returns singleton."""
        from verlex_server.gateway.core.results import get_result_manager

        rm1 = get_result_manager()
        rm2 = get_result_manager()

        assert rm1 is rm2

    def test_api_imports_result_manager(self):
        """Test that api.py can import ResultManager."""
        # This simulates what happens in execute_job
        from verlex_server.gateway.core.results import get_result_manager

        result_manager = get_result_manager()
        assert result_manager is not None

    @pytest.mark.asyncio
    async def test_result_manager_store_result_exists(self):
        """Test that store_result method exists on ResultManager."""
        from verlex_server.gateway.core.results import get_result_manager

        result_manager = get_result_manager()

        # Check that store_result method exists
        assert hasattr(result_manager, 'store_result')
        assert callable(result_manager.store_result)


class TestExecuteJobResultManagerIntegration:
    """Test that execute_job properly stores results via ResultManager."""

    def test_execute_job_code_contains_result_manager_call(self):
        """Verify _execute_job_locally function contains ResultManager store_result call."""
        import inspect

        from verlex_server.gateway.backend.api import _execute_job_locally

        source = inspect.getsource(_execute_job_locally)

        # Check that ResultManager is imported and used
        assert 'from verlex_server.gateway.core.results import get_result_manager' in source
        assert 'result_manager = get_result_manager()' in source
        assert 'result_manager.store_result' in source

    def test_api_module_has_result_manager_import(self):
        """Verify api.py contains the ResultManager import."""
        with open('verlex_server/gateway/backend/api.py') as f:
            content = f.read()

        # Check for the import and usage
        assert 'from verlex_server.gateway.core.results import get_result_manager' in content
        assert 'await result_manager.store_result(job_id, result)' in content


class TestAllFixesTogether:
    """Integration test that verifies both fixes work together."""

    def test_all_exports_available(self):
        """Test all new exports are available."""
        # Audit logging
        from verlex_server.gateway.backend import (
            AuditEvent,
            AuditEventType,
            AuditLogger,
            AuditMiddleware,
            AuditOutcome,
            AuditSeverity,
            create_audit_logger,
            get_audit_logger,
        )

        # ResultManager (already was available)
        from verlex_server.gateway.core.results import (
            ResultManager,
            get_result_manager,
        )

        # Verify all are not None
        assert all([
            AuditLogger,
            AuditMiddleware,
            AuditEventType,
            AuditSeverity,
            AuditOutcome,
            AuditEvent,
            get_audit_logger,
            create_audit_logger,
            get_result_manager,
            ResultManager,
        ])

    def test_api_app_fully_functional(self):
        """Test the FastAPI app is fully functional with all fixes."""
        from fastapi.testclient import TestClient

        from verlex_server.gateway.backend.api import create_app

        app = create_app()
        client = TestClient(app)

        # Health endpoint should work
        response = client.get("/health")
        assert response.status_code == 200
