"""Fetch content from a URL.

Retrieves and returns the content of a web page.
"""

import httpx

from core.pathways.models.tool import ToolOutput


async def run(
    url: str,
    timeout: int = 30,
    include_headers: bool = False,
) -> ToolOutput:
    """
    Args:
        url: URL to fetch
        timeout: Request timeout in seconds
        include_headers: Whether to include response headers.
    """
    if not url or not url.strip():
        return ToolOutput(success=False, error="url is required")

    # Using hoisted httpx import
    try:
        async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
            response = await client.get(url)

            if response.status_code >= 400:
                return ToolOutput(
                    success=False,
                    error=f"HTTP {response.status_code}",
                    data={"url": str(response.url), "status_code": response.status_code},
                )

            data: dict[str, object] = {
                "url": str(response.url),
                "status_code": int(response.status_code),
                "content": response.text,
            }

            if include_headers:
                data["headers"] = dict(response.headers)

            return ToolOutput(success=True, data=data)

    except httpx.TimeoutException:
        return ToolOutput(success=False, error=f"Request timed out after {timeout}s")
    except Exception as e:
        return ToolOutput(success=False, error=str(e))
