"""Fixtures for e2e agent tests.

Runs claude -p as a subprocess with the luca plugin loaded.
"""

from __future__ import annotations

import os
import subprocess
from pathlib import Path

import pytest

from .evaluator import AgentResult, parse_stream_json

# Project root — where .claude-plugin/ lives
PROJECT_ROOT = Path(__file__).resolve().parents[2]

# Model to use for e2e tests (haiku is cheapest/fastest)
E2E_MODEL = os.environ.get("E2E_MODEL", "haiku")

# Timeout per test case in seconds
E2E_TIMEOUT = int(os.environ.get("E2E_TIMEOUT", "120"))


@pytest.fixture(scope="session")
def plugin_dir() -> str:
    """Return the project root path for --plugin-dir."""
    return str(PROJECT_ROOT)


def run_agent(prompt: str, *, model: str = E2E_MODEL, timeout: int = E2E_TIMEOUT) -> AgentResult:
    """Run claude -p with the luca plugin and return parsed results.

    Runs from the home directory to avoid .mcp.json conflicts.
    """
    cmd = [
        "claude",
        "-p",
        "--plugin-dir", str(PROJECT_ROOT),
        "--output-format", "stream-json",
        "--verbose",
        "--model", model,
        "--dangerously-skip-permissions",
    ]

    try:
        proc = subprocess.run(
            cmd,
            input=prompt,
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=os.path.expanduser("~"),
        )
    except subprocess.TimeoutExpired as exc:
        result = AgentResult()
        result.is_error = True
        result.error_message = f"claude -p timed out after {timeout}s"
        # Try to parse any partial output
        if exc.stdout:
            raw = exc.stdout if isinstance(exc.stdout, str) else exc.stdout.decode()
            partial = parse_stream_json(raw)
            result.tools_called = partial.tools_called
            result.result_text = partial.result_text
        return result

    if proc.returncode != 0 and not proc.stdout.strip():
        result = AgentResult()
        result.is_error = True
        result.error_message = proc.stderr or f"claude exited with code {proc.returncode}"
        return result

    return parse_stream_json(proc.stdout)
