"""Unit tests for config module."""
import pytest


def test_settings_defaults(monkeypatch):
    """Settings load with expected defaults."""
    monkeypatch.delenv("POSTGRES_DSN", raising=False)
    monkeypatch.delenv("STOCK_ORACLE_URL", raising=False)

    # Reset lru_cache
    from libs.common import config
    config.get_settings.cache_clear()

    settings = config.Settings(
        postgres_dsn="postgresql+asyncpg://acef:acef@localhost:5432/acef",
        stock_oracle_url="http://localhost:18001",
    )
    assert settings.stock_oracle_url == "http://localhost:18001"
    assert settings.log_level == "INFO"
    assert settings.llm_enabled is False
    config.get_settings.cache_clear()


def test_log_level_normalized():
    from libs.common.config import Settings
    s = Settings(log_level="debug")
    assert s.log_level == "DEBUG"


def test_exhibit_cache_dir():
    from libs.common.config import Settings
    s = Settings(data_root="/tmp/acef")
    assert str(s.exhibit_cache_dir) == "/tmp/acef/cache/exhibits"


def test_parquet_dir():
    from libs.common.config import Settings
    s = Settings(data_root="/tmp/acef")
    assert str(s.parquet_dir) == "/tmp/acef/parquet"


@pytest.mark.unit
def test_get_symbols(tmp_path):
    """get_symbols returns list from YAML."""
    import yaml

    from libs.common.config import Settings

    symbols_file = tmp_path / "symbols.yaml"
    symbols_file.write_text(yaml.dump({"symbols": ["AAPL", "MSFT"]}))

    import os
    old = os.getcwd()
    os.chdir(tmp_path)
    (tmp_path / "configs").mkdir(exist_ok=True)
    (tmp_path / "configs" / "symbols.yaml").write_text(
        yaml.dump({"symbols": ["AAPL", "MSFT"]})
    )
    s = Settings()
    syms = s.get_symbols()
    os.chdir(old)
    # May return [] if configs/symbols.yaml not in cwd — just check type
    assert isinstance(syms, list)


@pytest.mark.unit
def test_symbols_file_configurable(tmp_path):
    """symbols_file field can point to a custom YAML file."""
    import yaml

    from libs.common.config import Settings

    custom = tmp_path / "custom_symbols.yaml"
    custom.write_text(yaml.dump({"symbols": ["CIEN", "CALX", "TENB"]}))

    s = Settings(symbols_file=str(custom))
    assert s.symbols_file == str(custom)
    syms = s.get_symbols()
    assert syms == ["CIEN", "CALX", "TENB"]


@pytest.mark.unit
def test_symbols_file_default():
    """Default symbols_file is configs/symbols.yaml."""
    from libs.common.config import Settings

    s = Settings()
    assert s.symbols_file == "configs/symbols.yaml"
