"""Tests for b2alpha.bridge scaffold."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import pytest

from b2alpha.bridge import AdapterRegistry, CompanyAgentProxy
from b2alpha.bridge.adapters import AcmeOrdersAdapter


def _mock_response(status: int, body: dict) -> MagicMock:
    resp = MagicMock()
    resp.status_code = status
    resp.json.return_value = body
    resp.text = str(body)
    return resp


class TestAdapterRegistry:
    def test_resolve(self):
        registry = AdapterRegistry()
        registry.register(AcmeOrdersAdapter())
        adapter = registry.resolve("order.create")
        assert adapter.name == "acme-orders"

    def test_missing_adapter_raises(self):
        registry = AdapterRegistry()
        with pytest.raises(KeyError, match="no adapter registered"):
            registry.resolve("inventory.get")


class TestCompanyAgentProxy:
    @patch("b2alpha.bridge.adapter.httpx.request")
    def test_dispatch_order_create(self, mock_request):
        mock_request.return_value = _mock_response(201, {"id": "ord_1", "status": "created"})

        registry = AdapterRegistry()
        registry.register(AcmeOrdersAdapter())
        proxy = CompanyAgentProxy(
            base_url="https://api.acme.example/v1",
            registry=registry,
            default_headers={"User-Agent": "test-proxy"},
        )

        result = proxy.dispatch(
            "order.create",
            params={"sku": "SKU-1", "quantity": 2, "customer_id": "cust_9"},
            metadata={"acme_api_key": "key123"},
        )

        assert result.ok is True
        assert result.status_code == 201
        assert result.adapter == "acme-orders"
        assert result.data["status"] == "created"

        kwargs = mock_request.call_args.kwargs
        assert mock_request.call_args.args[0] == "POST"
        assert mock_request.call_args.args[1] == "https://api.acme.example/v1/orders"
        assert kwargs["headers"]["User-Agent"] == "test-proxy"
        assert kwargs["headers"]["X-API-Key"] == "key123"
        assert kwargs["json"]["sku"] == "SKU-1"
        assert kwargs["json"]["quantity"] == 2

    @patch("b2alpha.bridge.adapter.httpx.request")
    def test_dispatch_order_status(self, mock_request):
        mock_request.return_value = _mock_response(200, {"id": "ord_1", "status": "shipped"})

        registry = AdapterRegistry()
        registry.register(AcmeOrdersAdapter())
        proxy = CompanyAgentProxy(
            base_url="https://api.acme.example/v1",
            registry=registry,
        )

        result = proxy.dispatch(
            "order.status",
            params={"order_id": "ord_1"},
        )

        assert result.ok is True
        assert result.data["status"] == "shipped"
        assert mock_request.call_args.args[0] == "GET"
        assert mock_request.call_args.args[1] == "https://api.acme.example/v1/orders/ord_1"

    def test_adapter_validation(self):
        registry = AdapterRegistry()
        registry.register(AcmeOrdersAdapter())
        proxy = CompanyAgentProxy(base_url="https://api.acme.example/v1", registry=registry)

        with pytest.raises(ValueError, match="requires param 'sku'"):
            proxy.dispatch("order.create", params={"quantity": 1})
