"""
Unit tests for veena3modal FastAPI app.

M1: Tests for /v1/tts/health endpoint and app creation.
"""

import pytest


class TestAppFactory:
    """Test app factory and basic structure."""

    def test_create_app_returns_fastapi_instance(self):
        """Ensure create_app() returns a FastAPI application."""
        from veena3modal.api.fastapi_app import create_app
        
        app = create_app()
        
        # Check it's a FastAPI app (has routes, title, version)
        assert hasattr(app, "routes")
        assert app.title == "Veena3 TTS (Modal)"
        assert app.version == "0.1.0"

    def test_create_app_has_health_route(self):
        """Ensure /v1/tts/health route exists."""
        from veena3modal.api.fastapi_app import create_app
        
        app = create_app()
        
        # Find health route
        route_paths = [r.path for r in app.routes if hasattr(r, "path")]
        assert "/v1/tts/health" in route_paths


class TestHealthEndpoint:
    """Test /v1/tts/health endpoint responses."""

    @pytest.fixture
    def client(self):
        """Create a test client for the FastAPI app."""
        from fastapi.testclient import TestClient
        from veena3modal.api.fastapi_app import create_app
        
        app = create_app()
        return TestClient(app)

    def test_health_returns_200(self, client):
        """Health endpoint should return 200 OK."""
        response = client.get("/v1/tts/health")
        assert response.status_code == 200

    def test_health_returns_expected_fields(self, client):
        """Health endpoint should return all required fields."""
        response = client.get("/v1/tts/health")
        data = response.json()
        
        # Required fields
        assert "status" in data
        assert "model_loaded" in data
        assert "model_version" in data
        assert "uptime_seconds" in data
        assert "gpu_available" in data
        assert "app_version" in data

    def test_health_status_is_valid(self, client):
        """Health status should be one of: healthy, degraded, unhealthy."""
        response = client.get("/v1/tts/health")
        data = response.json()
        
        assert data["status"] in ["healthy", "degraded", "unhealthy"]

    def test_health_model_not_loaded_initially(self, client):
        """Model should not be loaded by default (no runtime wired yet)."""
        response = client.get("/v1/tts/health")
        data = response.json()
        
        # Model not loaded until M3 wires the runtime
        assert data["model_loaded"] is False
        assert data["model_version"] == "not_loaded"

    def test_health_uptime_is_positive(self, client):
        """Uptime should be a non-negative number."""
        response = client.get("/v1/tts/health")
        data = response.json()
        
        assert isinstance(data["uptime_seconds"], (int, float))
        assert data["uptime_seconds"] >= 0

    def test_health_includes_version_headers(self, client):
        """Health response should include version headers."""
        response = client.get("/v1/tts/health")
        
        assert "X-Model-Version" in response.headers
        assert "X-App-Version" in response.headers
        assert response.headers["X-App-Version"] == "0.1.0"

    def test_health_content_type_is_json(self, client):
        """Health response should be JSON."""
        response = client.get("/v1/tts/health")
        
        assert "application/json" in response.headers.get("content-type", "")


class TestModelVersionHelpers:
    """Test model version getter/setter helpers."""

    def test_get_model_version_default(self):
        """get_model_version returns 'not_loaded' when not set."""
        from veena3modal.api import fastapi_app
        
        # Reset state
        fastapi_app._MODEL_VERSION = None
        
        assert fastapi_app.get_model_version() == "not_loaded"

    def test_set_and_get_model_version(self):
        """set_model_version updates the global, get_model_version retrieves it."""
        from veena3modal.api import fastapi_app
        
        # Reset and set
        fastapi_app._MODEL_VERSION = None
        fastapi_app.set_model_version("spark-tts-v1.2.3")
        
        assert fastapi_app.get_model_version() == "spark-tts-v1.2.3"
        
        # Clean up
        fastapi_app._MODEL_VERSION = None

