
"""Shared test fixtures.

Tests NEVER touch the real database, send real email, or call OpenAI:
- DATABASE_URL is pointed at a throwaway SQLite file *before* the app is imported
  (env vars override backend/.env).
- OpenAI is replaced by ``FakeOpenAI`` which replays scripted tool calls.
- Email sending is monkeypatched where a test needs it.
"""

from __future__ import annotations

import json
import os
import tempfile
from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace

_TMP = Path(tempfile.mkdtemp(prefix="leads-tests-"))
os.environ["DATABASE_URL"] = f"sqlite:///{_TMP / 'test.db'}"
os.environ["OPENAI_API_KEY"] = "test-key-not-real"
os.environ["OPENAI_MODEL"] = "gpt-5-nano"
os.environ["OPENAI_REASONING_EFFORT"] = "minimal"
os.environ["OPENAI_STT_MODEL"] = "gpt-4o-mini-transcribe"
os.environ["OPENAI_STT_LANGUAGE"] = "en"
# Never let a test fall through to a real mailbox
os.environ["EMAIL_PROVIDER"] = "smtp"
os.environ["SMTP_HOST"] = ""

import pytest  # noqa: E402

from app.agent import runner  # noqa: E402
from app.database import Base, SessionLocal, engine  # noqa: E402
import app.models  # noqa: E402,F401
from app.models import Lead  # noqa: E402
from app.services import build_follow_ups  # noqa: E402


# --------------------------------------------------------------------------- DB


@pytest.fixture()
def db():
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    session = SessionLocal()
    try:
        yield session
    finally:
        session.close()


def _add_lead(db, code, name, email, stage="New Lead", added=None):
    lead = Lead(
        lead_code=code,
        contact_name=name,
        client_email=email,
        website="https://example.com",
        date_added=added or date.today(),
        stage=stage,
    )
    lead.follow_ups = build_follow_ups(lead.date_added)
    db.add(lead)
    db.commit()
    db.refresh(lead)
    return lead


@pytest.fixture()
def leads(db):
    """Sarah (unique), two Toms (ambiguous), one overdue warm lead."""
    return {
        "sarah": _add_lead(db, "L-001", "Sarah Jenkins", "sarah@example.com", "Warm lead"),
        "tom_b": _add_lead(db, "L-002", "Tom Baker", "tom@example.com"),
        "tom_h": _add_lead(db, "L-003", "Tom Hardy", "hardy@example.com"),
        "old": _add_lead(
            db,
            "L-004",
            "Olivia Old",
            "olivia@example.com",
            "Warm lead",
            added=date.today() - timedelta(days=5),
        ),
    }


# ----------------------------------------------------------------- fake OpenAI


def tool_call(name: str, **args) -> SimpleNamespace:
    """One scripted model tool call."""
    tool_call.counter += 1
    return SimpleNamespace(
        id=f"call_{tool_call.counter}",
        type="function",
        function=SimpleNamespace(name=name, arguments=json.dumps(args)),
    )


tool_call.counter = 0


def text_reply(text: str) -> list:
    """A scripted round where the model answers with text (no tool call)."""
    return [SimpleNamespace(_text=text)]


class FakeOpenAI:
    """Replays one scripted response per chat.completions.create call.

    ``rounds`` is a list; each item is a list of ``tool_call(...)`` objects, or
    ``text_reply("...")`` for a plain text answer.
    """

    def __init__(self, rounds=None, transcript="Send the follow-up to Sarah Jenkins"):
        self.rounds = list(rounds or [])
        self.transcript = transcript
        self.chat_calls: list[dict] = []
        self.stt_calls: list[dict] = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create))
        self.audio = SimpleNamespace(transcriptions=SimpleNamespace(create=self._transcribe))

    def _create(self, **kwargs):
        self.chat_calls.append(kwargs)
        if not self.rounds:
            raise AssertionError("Model was called more times than scripted")
        calls = self.rounds.pop(0)
        if calls and hasattr(calls[0], "_text"):
            msg = SimpleNamespace(content=calls[0]._text, tool_calls=None)
            finish = "stop"
        else:
            msg = SimpleNamespace(content=None, tool_calls=calls)
            finish = "tool_calls"
        return SimpleNamespace(choices=[SimpleNamespace(message=msg, finish_reason=finish)])

    def _transcribe(self, **kwargs):
        self.stt_calls.append(kwargs)
        return SimpleNamespace(text=self.transcript)


@pytest.fixture()
def fake_openai(monkeypatch):
    """Install a FakeOpenAI. Call ``fake_openai(rounds, transcript=...)`` to script it."""

    def install(rounds=None, transcript="Send the follow-up to Sarah Jenkins"):
        fake = FakeOpenAI(rounds, transcript)
        monkeypatch.setattr(runner, "_openai_client", lambda: fake)
        return fake

    return install


@pytest.fixture()
def client(db, monkeypatch):
    """FastAPI TestClient bound to the throwaway DB (demo seed lead disabled)."""
    from fastapi.testclient import TestClient

    from app.main import app

    monkeypatch.setattr("app.main.seed_if_empty", lambda _db: None)

    with TestClient(app) as c:
        yield c
