import pytest

from src.server.models.config import (
    AppConfig,
    ConfigUpdate,
    LoggingConfig,
    NFOConfig,
    SchedulerConfig,
    ValidationResult,
)


def test_scheduler_defaults_and_validation():
    sched = SchedulerConfig()
    assert sched.enabled is True
    assert sched.interval_minutes == 60

    with pytest.raises(ValueError):
        SchedulerConfig(interval_minutes=0)


def test_logging_config_defaults_and_values():
    log = LoggingConfig()
    assert log.level == "INFO"
    assert log.file is None
    assert log.backup_count == 3


def test_appconfig_and_config_update_apply_to():
    base = AppConfig()

    upd = ConfigUpdate(
        scheduler=SchedulerConfig(enabled=False, interval_minutes=30)
    )
    new = upd.apply_to(base)
    assert isinstance(new, AppConfig)
    assert new.scheduler.enabled is False
    assert new.scheduler.interval_minutes == 30

    upd2 = ConfigUpdate(other={"b": 2})
    new2 = upd2.apply_to(base)
    assert new2.other.get("b") == 2


def test_backup_and_validation():
    cfg = AppConfig()
    # default backups disabled -> valid
    res: ValidationResult = cfg.validate_config()
    assert res.valid is True

    # enable backups but leave path empty -> invalid
    cfg.backup.enabled = True
    cfg.backup.path = ""
    res2 = cfg.validate_config()
    assert res2.valid is False
    assert any("backup.path" in e for e in res2.errors)


def test_nfo_config_defaults():
    """Test NFO configuration defaults."""
    nfo = NFOConfig()
    assert nfo.tmdb_api_key is None
    assert nfo.auto_create is False
    assert nfo.update_on_scan is False
    assert nfo.download_poster is True
    assert nfo.download_logo is True
    assert nfo.download_fanart is True
    assert nfo.image_size == "original"


def test_nfo_config_image_size_validation():
    """Test NFO image size validation."""
    # Valid sizes
    nfo1 = NFOConfig(image_size="original")
    assert nfo1.image_size == "original"
    
    nfo2 = NFOConfig(image_size="w500")
    assert nfo2.image_size == "w500"
    
    # Invalid size
    with pytest.raises(ValueError, match="invalid image size"):
        NFOConfig(image_size="invalid")


def test_appconfig_includes_nfo():
    """Test that AppConfig includes NFO configuration."""
    cfg = AppConfig()
    assert cfg.nfo is not None
    assert isinstance(cfg.nfo, NFOConfig)
    assert cfg.nfo.auto_create is False


def test_config_update_with_nfo():
    """Test ConfigUpdate can update NFO settings."""
    base = AppConfig()
    
    # Create NFO config update
    nfo_config = NFOConfig(
        tmdb_api_key="test_key_123",
        auto_create=True,
        image_size="w500"
    )
    
    upd = ConfigUpdate(nfo=nfo_config)
    new = upd.apply_to(base)
    
    assert new.nfo.tmdb_api_key == "test_key_123"
    assert new.nfo.auto_create is True
    assert new.nfo.image_size == "w500"
