"""HTTP request tool - Make HTTP API calls."""

from __future__ import annotations

from typing import Any

import httpx

from agenai.agent.tools.base import Tool, ToolResult


class HttpRequestTool(Tool):
    """Tool for making HTTP requests."""

    @property
    def name(self) -> str:
        return "http_request"

    @property
    def description(self) -> str:
        return "Make an HTTP request to a URL and return the response."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "url": {
                    "type": "string",
                    "description": "The URL to request",
                },
                "method": {
                    "type": "string",
                    "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"],
                    "description": "HTTP method (default: GET)",
                    "default": "GET",
                },
                "headers": {
                    "type": "object",
                    "description": "HTTP headers to include",
                    "additionalProperties": {"type": "string"},
                },
                "body": {
                    "type": "string",
                    "description": "Request body (for POST, PUT, PATCH)",
                },
                "timeout": {
                    "type": "integer",
                    "description": "Request timeout in seconds (default: 30)",
                    "default": 30,
                },
            },
            "required": ["url"],
        }

    def execute(
        self,
        url: str,
        method: str = "GET",
        headers: dict[str, str] | None = None,
        body: str | None = None,
        timeout: int = 30,
    ) -> ToolResult:
        """Make an HTTP request."""
        try:
            with httpx.Client(timeout=timeout) as client:
                response = client.request(
                    method=method,
                    url=url,
                    headers=headers,
                    content=body,
                )

            result_parts = [
                f"Status: {response.status_code}",
                f"Headers: {dict(response.headers)}",
            ]

            # Try to include response body
            try:
                body_text = response.text
                # Truncate very long responses
                max_body_len = 10000
                if len(body_text) > max_body_len:
                    body_text = body_text[:max_body_len] + "\n...(truncated)"
                result_parts.append(f"Body:\n{body_text}")
            except Exception:
                result_parts.append("Body: (unable to decode)")

            output = "\n".join(result_parts)

            if response.is_success:
                return ToolResult.ok(output)
            else:
                return ToolResult.fail(output)

        except httpx.TimeoutException:
            return ToolResult.fail(f"Request timed out after {timeout} seconds")
        except httpx.RequestError as e:
            return ToolResult.fail(f"Request error: {e}")
        except Exception as e:
            return ToolResult.fail(f"Error making request: {e}")
