import json
from pathlib import Path

import pytest

import app.narrate as narrate
from app.ollama_client import ModelError

VALID = json.loads((Path(__file__).parent / "fixtures" / "canon_log_valid.json").read_text())


def test_run_returns_prose_and_logs_success(monkeypatch):
    seen = {}

    def fake_chat(model, messages, options, *, think=None):
        seen.update(model=model, messages=messages, options=options, think=think)
        return "You stand on the wharf. [FACT: the gulls have gone quiet]"

    logs = []
    monkeypatch.setattr(narrate.ollama_client, "chat", fake_chat)
    monkeypatch.setattr(narrate.call_log, "record", lambda **kw: logs.append(kw))

    out = narrate.run(VALID)
    assert out.startswith("You stand on the wharf.")
    assert seen["model"] == "qwen3.5:latest"
    assert seen["think"] is False
    assert seen["messages"][0]["role"] == "system"
    assert seen["messages"][1]["role"] == "user"
    assert "seed" in seen["options"]
    assert logs and logs[0]["ok"] is True and logs[0]["response"] == out


def test_run_logs_failure_and_reraises(monkeypatch):
    def boom(*args, **kwargs):
        raise ModelError("upstream down")

    logs = []
    monkeypatch.setattr(narrate.ollama_client, "chat", boom)
    monkeypatch.setattr(narrate.call_log, "record", lambda **kw: logs.append(kw))

    with pytest.raises(ModelError):
        narrate.run(VALID)
    assert logs and logs[0]["ok"] is False and "down" in logs[0]["error"]
