from __future__ import annotations

import asyncio
import importlib.util
import sys
from pathlib import Path

import pytest


def _load_module(path: Path, name: str):
    spec = importlib.util.spec_from_file_location(name, path)
    assert spec is not None
    assert spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


def test_minimal_coding_example_reports_agent_error_message(
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    module = _load_module(
        Path("examples/coding/01_minimal.py"),
        "examples_coding_01_minimal",
    )
    summary_called = False

    class _FakeSessionManager:
        def get_cwd(self) -> str:
            return "/tmp/project"

    class _FakeAgent:
        error_message = "missing api key"

    class _FakeSession:
        def __init__(self) -> None:
            self.agent = _FakeAgent()
            self.session_manager = _FakeSessionManager()

        async def prompt(self, user_input: str) -> None:
            assert user_input

    monkeypatch.setattr(module, "CalcTool", lambda: object())
    monkeypatch.setattr(module, "build_kimi_model", lambda: object())
    monkeypatch.setattr(
        module,
        "describe_model",
        lambda model: {
            "provider": "moonshot",
            "model": "kimi-k2.5",
            "api": "anthropic-messages",
            "base_url": "https://api.moonshot.cn/anthropic",
        },
    )
    monkeypatch.setattr(module, "create_kimi_session", lambda **kwargs: _FakeSession())
    monkeypatch.setattr(module, "attach_stream_printer", lambda session: None)

    def _mark_summary_called(session) -> None:
        nonlocal summary_called
        summary_called = True

    monkeypatch.setattr(module, "print_message_summary", _mark_summary_called)

    with pytest.raises(SystemExit) as exc_info:
        asyncio.run(module.main())

    assert exc_info.value.code == 1
    captured = capsys.readouterr()
    assert "missing api key" in captured.err
    assert summary_called is False
