"""Tests for NFO service dependency with config fallback.

Tests that get_nfo_service() correctly loads TMDB API key from config.json
when it's not in settings (e.g., after server reload in development).
"""
from unittest.mock import MagicMock, patch

import pytest
from fastapi import HTTPException

from src.config.settings import settings
from src.server.api.nfo import get_nfo_service
from src.server.models.config import AppConfig, NFOConfig


def _reset_factory_cache():
    """Reset the NFO factory singleton so each test gets a clean factory."""
    import src.core.services.nfo_factory as factory_mod
    factory_mod._factory_instance = None


@pytest.mark.asyncio
async def test_get_nfo_service_with_settings_tmdb_key():
    """Test get_nfo_service when TMDB key is in settings."""
    _reset_factory_cache()
    original_key = settings.tmdb_api_key
    settings.tmdb_api_key = "test_api_key_from_settings"
    
    try:
        nfo_service = await get_nfo_service()
        assert nfo_service is not None
        assert nfo_service.tmdb_client.api_key == "test_api_key_from_settings"
    finally:
        settings.tmdb_api_key = original_key
        _reset_factory_cache()


@pytest.mark.asyncio
async def test_get_nfo_service_fallback_to_config():
    """Test get_nfo_service falls back to config.json when key not in settings."""
    _reset_factory_cache()
    original_key = settings.tmdb_api_key
    settings.tmdb_api_key = None
    
    try:
        mock_config = AppConfig(
            name="Test",
            data_dir="data",
            nfo=NFOConfig(
                tmdb_api_key="test_api_key_from_config",
                auto_create=False,
                update_on_scan=False
            )
        )
        
        with patch('src.server.services.config_service.get_config_service') as mock_get_config:
            mock_config_service = MagicMock()
            mock_config_service.load_config.return_value = mock_config
            mock_get_config.return_value = mock_config_service
            
            nfo_service = await get_nfo_service()
            assert nfo_service is not None
            assert nfo_service.tmdb_client.api_key == "test_api_key_from_config"
    finally:
        settings.tmdb_api_key = original_key
        _reset_factory_cache()


@pytest.mark.asyncio
async def test_get_nfo_service_no_key_raises_503():
    """Test get_nfo_service raises 503 when no TMDB key available."""
    _reset_factory_cache()
    original_key = settings.tmdb_api_key
    settings.tmdb_api_key = None
    
    try:
        mock_config = AppConfig(
            name="Test",
            data_dir="data",
            nfo=NFOConfig(
                tmdb_api_key=None,
                auto_create=False,
                update_on_scan=False
            )
        )
        
        with patch('src.server.services.config_service.get_config_service') as mock_get_config:
            mock_config_service = MagicMock()
            mock_config_service.load_config.return_value = mock_config
            mock_get_config.return_value = mock_config_service
            
            with pytest.raises(HTTPException) as exc_info:
                await get_nfo_service()
            
            assert exc_info.value.status_code == 503
            assert "TMDB API key not configured" in exc_info.value.detail
    finally:
        settings.tmdb_api_key = original_key
        _reset_factory_cache()


@pytest.mark.asyncio
async def test_get_nfo_service_config_load_fails_raises_503():
    """Test get_nfo_service raises 503 when config loading fails."""
    _reset_factory_cache()
    original_key = settings.tmdb_api_key
    settings.tmdb_api_key = None
    
    try:
        with patch('src.server.services.config_service.get_config_service') as mock_get_config:
            mock_get_config.side_effect = Exception("Config file not found")
            
            with pytest.raises(HTTPException) as exc_info:
                await get_nfo_service()
            
            assert exc_info.value.status_code == 503
            assert "TMDB API key not configured" in exc_info.value.detail
    finally:
        settings.tmdb_api_key = original_key
        _reset_factory_cache()
