"""
URL Reader Tool

Allows the AI agent to fetch and read content from web pages.
"""

from pathlib import Path
from typing import Optional
import httpx
from bs4 import BeautifulSoup

from ai_coder.tools.base import Tool, ToolResult, ToolResultStatus


class URLReaderTool(Tool):
    """Read content from a web URL."""

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

    @property
    def description(self) -> str:
        return """Fetch and read the text content from a web page URL.
    
Use this tool when you need to:
- Read documentation from a URL
- Fetch code examples from GitHub or other sites
- Read API references
- Get detailed information from a search result

Parameters:
- url (required): The URL to fetch content from
- max_chars (optional): Maximum characters to return (default: 8000)"""

    def execute(self, url: str, max_chars: int = 8000, **kwargs) -> ToolResult:
        """Fetch and parse content from URL."""
        try:
            # Validate URL
            if not url.startswith(("http://", "https://")):
                return ToolResult.error("Invalid URL. Must start with http:// or https://")
            
            # Fetch the page
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
            }
            
            with httpx.Client(timeout=30, follow_redirects=True) as client:
                response = client.get(url, headers=headers)
                response.raise_for_status()
            
            content_type = response.headers.get("content-type", "")
            
            # Handle plain text
            if "text/plain" in content_type:
                text = response.text[:max_chars]
                return ToolResult.success(f"Content from {url}:\n\n{text}")
            
            # Parse HTML
            soup = BeautifulSoup(response.text, "lxml")
            
            # Remove script and style elements
            for element in soup(["script", "style", "nav", "footer", "header"]):
                element.decompose()
            
            # Get text content
            text = soup.get_text(separator="\n", strip=True)
            
            # Clean up whitespace
            lines = [line.strip() for line in text.splitlines() if line.strip()]
            text = "\n".join(lines)
            
            # Truncate if needed
            if len(text) > max_chars:
                text = text[:max_chars] + f"\n\n... (truncated, {len(text) - max_chars} more chars)"
            
            return ToolResult.success(f"Content from {url}:\n\n{text}")
            
        except httpx.HTTPStatusError as e:
            return ToolResult.error(f"HTTP error {e.response.status_code}: {e.response.reason_phrase}")
        except httpx.TimeoutException:
            return ToolResult.error("Request timed out")
        except Exception as e:
            return ToolResult.error(f"Failed to read URL: {str(e)}")
