"""Tests for mantara_client (skip-paths only — no live OpenAI calls)."""

import os
from pathlib import Path

import pytest

from pipeline.mantara_client import call_mantara


def test_client_skips_without_api_key(monkeypatch) -> None:
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)
    monkeypatch.setenv("MANTARA_BACKEND", "openai")
    result = call_mantara("dummy input")
    assert result["status"] == "skipped"
    assert "OPENAI_API_KEY" in result["skip_reason"]
    assert result["schema_json"] is None


def test_client_skips_when_engine_path_missing(monkeypatch, tmp_path) -> None:
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
    monkeypatch.setenv("MANTARA_ENGINE_PATH", str(tmp_path / "nope"))
    result = call_mantara("dummy input")
    assert result["status"] == "error"
    skip = (result["skip_reason"] or "").lower()
    assert ("not found" in skip) or ("does not contain" in skip)


def test_client_enforces_cost_cap(monkeypatch) -> None:
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
    monkeypatch.setenv("MANTARA_BACKEND", "openai")
    # Build a huge input that will trigger the pre-flight cost guard
    huge_input = "x" * 10_000_000  # 2.5M tokens estimate × 3 calls × $10/1M
    result = call_mantara(huge_input, cost_cap_usd=0.05)
    assert result["status"] == "skipped"
    assert "cost" in result["skip_reason"].lower()


def test_client_accepts_model_override(monkeypatch) -> None:
    """Passes the --model arg through and restores env after."""
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)
    monkeypatch.setenv("MANTARA_BACKEND", "openai")
    saved = os.environ.get("MANTARA_MODEL")
    result = call_mantara("dummy", model="gpt-4o-mini")
    # Will skip (no API key) but the model override path is exercised
    assert result["status"] == "skipped"
    # Env should be restored
    assert os.environ.get("MANTARA_MODEL") == saved
