"""Real LLM connection tests via OpenRouter.

These tests require:
  - ~/Projects/.env with OPENROUTER_KEY=sk-or-v1-...
  - Network access to https://openrouter.ai/api/v1

Skip with: pytest -m "not llm_real"
"""

import os
from pathlib import Path

import pytest
from dotenv import load_dotenv
from returns.result import Success

# Load OpenRouter key from ~/Projects/.env
load_dotenv(Path.home() / "Projects" / ".env")

# Wire OPENROUTER_KEY → OPENAI_API_KEY for PydanticAI's openai provider
_or_key = os.environ.get("OPENROUTER_KEY", "")
if _or_key and not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = _or_key
    os.environ["OPENAI_BASE_URL"] = "https://openrouter.ai/api/v1"

pytestmark = pytest.mark.llm_real

FIXTURES_DIR = Path(__file__).parent / "fixtures"


def _has_openrouter_key() -> bool:
    return bool(os.environ.get("OPENROUTER_KEY") or os.environ.get("OPENAI_API_KEY"))


skip_no_key = pytest.mark.skipif(
    not _has_openrouter_key(),
    reason="OPENROUTER_KEY or OPENAI_API_KEY not set",
)


@skip_no_key
@pytest.mark.asyncio
async def test_pydantic_ai_agent_creation():
    """Verify PydanticAI Agent can be created with OpenRouter model string."""
    from anima.core.schemas import PersonaSpec
    from anima.shell.agent import create_agent

    persona = PersonaSpec(
        id="ping-test",
        description="A test persona.",
        prompt="Respond with exactly: PONG",
        model="openai:gpt-5.2",
    )
    result = await create_agent(persona)
    assert isinstance(result, Success), f"Agent creation failed: {result}"


@skip_no_key
@pytest.mark.asyncio
async def test_real_llm_roundtrip():
    """End-to-end: send a prompt to OpenRouter and get a response."""
    from pydantic_ai import Agent

    agent = Agent(
        model="openai:gpt-5.2",
        system_prompt="You are a test agent. Respond with exactly one word: PONG",
    )
    result = await agent.run("PING")
    assert result.output is not None, "No output from LLM"
    assert len(result.output) > 0, "Empty output from LLM"
    # Relaxed check — LLM may add punctuation
    assert "PONG" in result.output.upper(), f"Unexpected response: {result.output}"


@skip_no_key
@pytest.mark.asyncio
async def test_real_llm_token_tracking():
    """Verify token usage is reported after a real LLM call."""
    from pydantic_ai import Agent

    agent = Agent(
        model="openai:gpt-5.2",
        system_prompt="Respond with exactly: OK",
    )
    result = await agent.run("test")
    usage = result.usage()
    assert usage.total_tokens > 0, f"Expected tokens > 0, got {usage.total_tokens}"
    assert usage.input_tokens > 0, "No input tokens tracked"
    assert usage.output_tokens > 0, "No output tokens tracked"


@skip_no_key
@pytest.mark.asyncio
async def test_persona_file_roundtrip():
    """Load persona from fixture JSON and create agent."""
    import json

    from anima.core.schemas import PersonaSpec
    from anima.shell.agent import create_agent

    persona_path = FIXTURES_DIR / "persona_openrouter.json"
    assert persona_path.exists(), f"Fixture not found: {persona_path}"

    persona_data = json.loads(persona_path.read_text())
    persona = PersonaSpec(**persona_data)

    assert persona.model == "openai:gpt-5.2"
    assert persona.id == "openrouter-test"

    result = await create_agent(persona)
    assert isinstance(result, Success), f"Agent creation from fixture failed: {result}"
