from __future__ import annotations

import json
from collections.abc import Callable
from typing import Any

import httpx
import pytest

from mcp_server_propel.propel_client import PropelClient


def make_mock_transport(
    handler: Callable[[httpx.Request], httpx.Response],
) -> httpx.MockTransport:
    return httpx.MockTransport(handler)


async def make_propel_client(transport: httpx.MockTransport) -> PropelClient:
    client = PropelClient(api_token="rev_test_token", base_url="https://api.test")
    await client._client.aclose()
    client._client = httpx.AsyncClient(
        transport=transport,
        base_url="https://api.test",
        headers={
            "Authorization": "Bearer rev_test_token",
            "Content-Type": "application/json",
        },
        timeout=httpx.Timeout(30.0),
    )
    return client


SAMPLE_QUEUED_RESPONSE: dict[str, Any] = {
    "review_id": "abc-123",
    "status": "queued",
    "repository": "myorg/myrepo",
    "base_commit": "",
    "created_at": "2025-02-16T10:30:00Z",
    "updated_at": "2025-02-16T10:30:00Z",
    "started_at": None,
    "completed_at": None,
    "comments": [],
    "error": None,
}

SAMPLE_RUNNING_RESPONSE: dict[str, Any] = {
    **SAMPLE_QUEUED_RESPONSE,
    "status": "running",
    "started_at": "2025-02-16T10:30:05Z",
    "updated_at": "2025-02-16T10:30:05Z",
}

SAMPLE_COMPLETED_RESPONSE: dict[str, Any] = {
    "review_id": "abc-123",
    "status": "completed",
    "repository": "myorg/myrepo",
    "base_commit": "",
    "created_at": "2025-02-16T10:30:00Z",
    "updated_at": "2025-02-16T10:35:00Z",
    "started_at": "2025-02-16T10:30:05Z",
    "completed_at": "2025-02-16T10:35:00Z",
    "comments": [
        {
            "file_path": "src/app.py",
            "line": 42,
            "message": "Consider using a list comprehension for better performance.",
            "severity": "recommended",
        },
        {
            "file_path": "src/utils.py",
            "line": 15,
            "message": "Add error handling for edge cases.",
            "severity": "important",
        },
    ],
    "error": None,
}

SAMPLE_COMPLETED_NO_COMMENTS_RESPONSE: dict[str, Any] = {
    **SAMPLE_COMPLETED_RESPONSE,
    "comments": [],
}

SAMPLE_FAILED_RESPONSE: dict[str, Any] = {
    "review_id": "abc-123",
    "status": "failed",
    "repository": "myorg/myrepo",
    "base_commit": "",
    "created_at": "2025-02-16T10:30:00Z",
    "updated_at": "2025-02-16T10:31:00Z",
    "started_at": "2025-02-16T10:30:05Z",
    "completed_at": "2025-02-16T10:31:00Z",
    "comments": [],
    "error": {
        "code": "generation_failed",
        "message": "Review generation failed due to an internal error.",
    },
}
