"""Tests for the unified action client."""

from __future__ import annotations

import httpx
import pytest

from torivers_sdk.context.actions import ActionClient, ActionError


class _FakeClient:
    def __init__(self, response: httpx.Response):
        self._response = response
        self.last_request: dict | None = None

    def __enter__(self) -> "_FakeClient":
        return self

    def __exit__(self, exc_type, exc, tb) -> None:
        return None

    def post(self, url: str, headers: dict, json: dict) -> httpx.Response:
        self.last_request = {
            "url": url,
            "headers": headers,
            "json": json,
        }
        return self._response


def _response(status_code: int, body: str) -> httpx.Response:
    return httpx.Response(
        status_code=status_code,
        content=body.encode("utf-8"),
        request=httpx.Request("POST", "https://example.com/api/action/execute"),
    )


def test_get_default_requires_runtime_env(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("TORIVERS_ACTION_PROXY_URL", raising=False)
    monkeypatch.delenv("TORIVERS_ACTION_TOKEN", raising=False)
    with pytest.raises(ActionError):
        ActionClient.get_default()


def test_execute_success(monkeypatch: pytest.MonkeyPatch) -> None:
    response = _response(
        200,
        '{"success": true, "action": "log.write", "data": {"log_id": "log-1"}}',
    )
    fake_client = _FakeClient(response)
    monkeypatch.setattr(
        "torivers_sdk.context.actions.httpx.Client",
        lambda timeout: fake_client,
    )

    client = ActionClient(base_url="https://proxy.example.com", token="tok")
    data = client.execute("log.write", {"level": "info", "title": "Hello"})

    assert data["log_id"] == "log-1"
    assert fake_client.last_request is not None
    assert fake_client.last_request["url"].endswith("/api/action/execute")
    assert fake_client.last_request["headers"]["Authorization"] == "Bearer tok"


def test_execute_http_error(monkeypatch: pytest.MonkeyPatch) -> None:
    response = _response(403, '{"detail":"forbidden"}')
    fake_client = _FakeClient(response)
    monkeypatch.setattr(
        "torivers_sdk.context.actions.httpx.Client",
        lambda timeout: fake_client,
    )

    client = ActionClient(base_url="https://proxy.example.com", token="tok")
    with pytest.raises(ActionError):
        client.execute("artifact.record", {"artifact_type": "chart"})
