"""Protocol compatibility: transfer HTTP routes must not regress control-plane surfaces.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Bulk upload/download use dedicated /api/transfer/* HTTP routes; JSON-RPC, /api/async,
and /ws remain the control plane (tech spec Decisions 10–11, 13).
"""

from __future__ import annotations

from typing import Any

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from mcp_proxy_adapter.api.core.app_factory_routes import setup_routes
from mcp_proxy_adapter.commands.builtin_commands import register_builtin_commands
from mcp_proxy_adapter.core.delivery.terminal_replay_store import TerminalReplayStore
from mcp_proxy_adapter.core.delivery.ws_delivery_manager import WsDeliveryManager
from mcp_proxy_adapter.core.job_push.events import ACTION_SUBSCRIBE_ERROR
from mcp_proxy_adapter.core.job_push.subscriptions import SubscriberRegistry
from mcp_proxy_adapter.transfer.server_store import TransferServerStore

_SHA = "7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9"


@pytest.fixture
def compatibility_app_client(
    tmp_path: Any, monkeypatch: pytest.MonkeyPatch
) -> TestClient:
    from mcp_proxy_adapter.api import handlers as handlers_mod

    store = TransferServerStore(
        storage_dir=str(tmp_path / "tstore"),
        session_ttl_seconds=3600,
        max_file_size_bytes=10737418240,
        default_chunk_size_bytes=1048576,
        max_chunk_size_bytes=8388608,
    )
    monkeypatch.setattr(handlers_mod, "_CACHED_TRANSFER_STORE", None)
    monkeypatch.setattr(handlers_mod, "get_transfer_store", lambda: store)

    app = FastAPI()
    register_builtin_commands()
    setup_routes(app)
    registry = SubscriberRegistry()
    replay = TerminalReplayStore()
    manager = WsDeliveryManager(registry, replay)
    app.state.job_push_registry = registry
    app.state.ws_delivery_manager = manager
    return TestClient(app)


def test_transfer_routes_do_not_break_existing_http_surfaces(
    compatibility_app_client: TestClient,
) -> None:
    h = compatibility_app_client.get("/health")
    assert h.status_code == 200
    c = compatibility_app_client.get("/commands")
    assert c.status_code == 200
    body = c.json()
    assert "commands" in body or isinstance(body.get("commands"), list)


def test_transfer_routes_do_not_break_jsonrpc_execution(
    compatibility_app_client: TestClient,
) -> None:
    r = compatibility_app_client.post(
        "/api/jsonrpc",
        json={"jsonrpc": "2.0", "method": "help", "params": {}, "id": 1},
    )
    assert r.status_code == 200
    data = r.json()
    assert data.get("jsonrpc") == "2.0"
    assert "result" in data
    assert data["result"].get("success") is True


def test_transfer_routes_do_not_break_async_http_acceptance(
    compatibility_app_client: TestClient,
) -> None:
    r = compatibility_app_client.post(
        "/api/jsonrpc",
        json={
            "jsonrpc": "2.0",
            "method": "execute_async",
            "params": {"command": "echo", "params": {"message": "compat"}},
            "id": 2,
        },
    )
    assert r.status_code == 200
    data = r.json()
    assert data.get("result", {}).get("accepted") is True
    assert data.get("result", {}).get("ws_id")


def test_transfer_routes_do_not_break_websocket_job_push(
    compatibility_app_client: TestClient,
) -> None:
    """Prove /ws handler still runs after transfer routes (typed subscribe protocol)."""
    with compatibility_app_client.websocket_connect("/ws") as ws:
        ws.send_json({"action": "subscribe"})
        first = ws.receive_json()
        assert first.get("action") == ACTION_SUBSCRIBE_ERROR
