import pytest
from pydantic import ValidationError

from app.core.config import Settings


def test_settings_defaults_for_local_development():
    settings = Settings(
        _env_file=None,
        ENVIRONMENT="development",
        OPENAI_API_KEY="",
    )
    assert settings.APP_NAME == "RAG Service"
    assert settings.PORT == 6005
    assert settings.DATABASE_NAME == "adpilot_rag"
    assert settings.INDEXING_RUNS_DATABASE == "adpilot_repo_sync"
    assert settings.EMBEDDING_RETRIEVAL_SERVICE_URL == "http://localhost:6004"
    settings.validate_runtime()


def test_settings_accepts_env_alias():
    settings = Settings(_env_file=None, ENV="local")
    assert settings.resolved_environment() == "local"
    assert settings.is_local()


def test_validate_runtime_requires_secrets_in_production():
    settings = Settings(
        _env_file=None,
        ENVIRONMENT="production",
        OPENAI_API_KEY="",
        MONGO_URI="",
    )
    with pytest.raises(ValueError, match="Missing required configuration"):
        settings.validate_runtime()


def test_validate_runtime_rejects_unsupported_classifier():
    settings = Settings(
        _env_file=None,
        ENVIRONMENT="production",
        INTENT_CLASSIFIER="llm-only",
        OPENAI_API_KEY="sk-test",
        MONGO_URI="mongodb://localhost:27017",
        EMBEDDING_RETRIEVAL_SERVICE_URL="http://localhost:6004",
    )
    with pytest.raises(ValueError, match="Unsupported INTENT_CLASSIFIER"):
        settings.validate_runtime()


def test_invalid_top_k():
    with pytest.raises(ValidationError):
        Settings(_env_file=None, QUERY_DEFAULT_TOP_K=0)


def test_invalid_score_threshold():
    with pytest.raises(ValidationError):
        Settings(_env_file=None, QUERY_DEFAULT_SCORE_THRESHOLD=1.5)
