from __future__ import annotations

import pytest

from openkite.config import SettingsError, load_settings


REQUIRED_ENV = [
    "OPENAI_API_KEY",
    "FIRECRAWL_API_KEY",
    "OPENKITE_MODEL",
    "ZERODHA_MCP_SSE_URL",
    "OPENKITE_DB_PATH",
    "OPENKITE_HOST",
    "OPENKITE_PORT",
    "OPENKITE_SHARE",
]


def _clear_env(monkeypatch: pytest.MonkeyPatch) -> None:
    for name in REQUIRED_ENV:
        monkeypatch.delenv(name, raising=False)


def test_load_settings_success(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
    _clear_env(monkeypatch)

    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
    monkeypatch.setenv("FIRECRAWL_API_KEY", "fc-test")
    monkeypatch.setenv("OPENKITE_MODEL", "gpt-5.4")
    monkeypatch.setenv("ZERODHA_MCP_SSE_URL", "https://mcp.kite.trade/sse")
    monkeypatch.setenv("OPENKITE_DB_PATH", str(tmp_path / "chat_history.db"))
    monkeypatch.setenv("OPENKITE_HOST", "127.0.0.1")
    monkeypatch.setenv("OPENKITE_PORT", "7860")
    monkeypatch.setenv("OPENKITE_SHARE", "false")

    settings = load_settings()

    assert settings.openai_api_key == "sk-test"
    assert settings.firecrawl_api_key == "fc-test"
    assert settings.model == "gpt-5.4"
    assert settings.port == 7860
    assert settings.share is False


def test_missing_required_env(monkeypatch: pytest.MonkeyPatch) -> None:
    _clear_env(monkeypatch)

    with pytest.raises(SettingsError):
        load_settings()
