from __future__ import annotations

from typer.testing import CliRunner
from fastapi.testclient import TestClient

import eightmem.cli.main as cli_main
import eightmem.ui.app as ui_app
from eightmem.cli.main import app
from eightmem.ui.app import create_app


runner = CliRunner()


class _FakeResult:
    def __init__(self, text: str = "TEST_OK") -> None:
        self.model = "qwen2.5:14b"
        self.text = text
        self.text_source = "response"
        self.done = True
        self.done_reason = "stop"
        self.eval_count = 1
        self.eval_duration = 1
        self.raw = {}


def test_cli_loads_default_model_from_local_env(fake_home, monkeypatch, tmp_path):
    monkeypatch.chdir(tmp_path)
    (tmp_path / ".env").write_text("DEFAULT_LLM_FALLBACK_MODEL=qwen2.5:14b\n", encoding="utf-8")
    monkeypatch.delenv("DEFAULT_LLM_FALLBACK_MODEL", raising=False)
    seen: dict[str, str] = {}

    def _fake_generate_text(**kwargs):
        seen["model"] = kwargs["model"]
        return _FakeResult()

    monkeypatch.setattr(cli_main, "generate_text", _fake_generate_text)
    result = runner.invoke(app, ["test-ollama", "--no-memory"])

    assert result.exit_code == 0
    assert seen["model"] == "qwen2.5:14b"
    assert "model: qwen2.5:14b" in result.stdout


def test_readyz_loads_default_model_from_local_env(fake_home, monkeypatch, tmp_path):
    monkeypatch.chdir(tmp_path)
    (tmp_path / ".env").write_text("DEFAULT_LLM_FALLBACK_MODEL=qwen2.5:14b\n", encoding="utf-8")
    monkeypatch.delenv("DEFAULT_LLM_FALLBACK_MODEL", raising=False)
    monkeypatch.delenv("TELEGRAM_BOT_TOKEN", raising=False)
    monkeypatch.setattr(ui_app, "check_ollama_backend", lambda: (True, None))
    monkeypatch.setattr(ui_app, "resolve_base_url", lambda: "http://localhost:11434")

    client = TestClient(create_app())
    ready = client.get("/readyz")

    assert ready.status_code == 200
    assert ready.json()["llm_default_model"] == "qwen2.5:14b"
