"""
Agentic web browsing — fetch pages, analyze with AI.
"""

import re

from elgringo.cli.colors import Colors


def normalize_url(url: str) -> str:
    """Ensure URL has a scheme."""
    if not url.startswith(("http://", "https://")):
        url = "http://" + url
    return url


async def fetch_url(url: str) -> dict:
    """Fetch a URL and return status, content, timing."""
    import time as _time
    import urllib.request
    import urllib.error

    url = normalize_url(url)
    start = _time.time()
    result = {"url": url, "status": 0, "content": "", "error": "", "time": 0.0}

    try:
        req = urllib.request.Request(url, headers={"User-Agent": "ElGringo/1.1"})
        with urllib.request.urlopen(req, timeout=15) as resp:
            result["status"] = resp.status
            result["content"] = resp.read().decode("utf-8", errors="replace")[:50000]
    except urllib.error.HTTPError as e:
        result["status"] = e.code
        try:
            result["content"] = e.read().decode("utf-8", errors="replace")[:10000]
        except Exception:
            pass
        result["error"] = str(e)
    except urllib.error.URLError as e:
        result["error"] = str(e.reason)
    except Exception as e:
        result["error"] = str(e)

    result["time"] = round(_time.time() - start, 2)
    return result


async def run_browse(url: str, instruction: str = ""):
    """Agentic web browsing — fetch a page, analyze with AI."""
    from elgringo.cli.run_task import run_single_task

    url = normalize_url(url)

    print(f"\n{Colors.BOLD}{'=' * 60}{Colors.RESET}")
    print(f"{Colors.CYAN}  EL GRINGO — BROWSE{Colors.RESET}")
    print(f"{Colors.BOLD}{'=' * 60}{Colors.RESET}")
    print(f"\n  {Colors.DIM}{url}{Colors.RESET}")
    if instruction:
        print(f"  {Colors.DIM}Instruction: {instruction}{Colors.RESET}")
    print()

    # Fetch the page
    print(f"  {Colors.GREEN}[1]{Colors.RESET} Fetching page...")
    page = await fetch_url(url)

    if page["error"] and page["status"] == 0:
        print(f"  {Colors.RED}Failed to reach {url}: {page['error']}{Colors.RESET}\n")
        return

    status_color = Colors.GREEN if page["status"] < 400 else Colors.RED
    print(f"  {Colors.GREEN}[2]{Colors.RESET} Status: {status_color}{page['status']}{Colors.RESET} ({page['time']}s)")

    content = page["content"]

    # Strip HTML tags for readability
    text_content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL | re.IGNORECASE)
    text_content = re.sub(r'<style[^>]*>.*?</style>', '', text_content, flags=re.DOTALL | re.IGNORECASE)
    text_content = re.sub(r'<[^>]+>', ' ', text_content)
    text_content = re.sub(r'\s+', ' ', text_content).strip()[:10000]

    # Try screenshot if Playwright available
    screenshot_path = ""
    try:
        from elgringo.tools.browser import BrowserTools
        browser = BrowserTools()
        screenshot_result = await browser._take_screenshot(url, "/tmp/elgringo_browse.png")
        if screenshot_result.success:
            screenshot_path = "/tmp/elgringo_browse.png"
            print(f"  {Colors.GREEN}[3]{Colors.RESET} Screenshot saved: {screenshot_path}")
    except Exception:
        pass

    # Build AI prompt
    if instruction:
        prompt = (
            f"I browsed {url} (HTTP {page['status']}).\n\n"
            f"Page content:\n```\n{text_content}\n```\n\n"
            f"User instruction: {instruction}\n\n"
            f"Analyze the page and respond to the instruction."
        )
    else:
        prompt = (
            f"I browsed {url} (HTTP {page['status']}).\n\n"
            f"Page content:\n```\n{text_content}\n```\n\n"
            f"Analyze this page: what is it, what does it show, any errors or issues, "
            f"and key observations."
        )

    print(f"  {Colors.GREEN}[{'4' if screenshot_path else '3'}]{Colors.RESET} Analyzing with AI team...")

    from elgringo.orchestrator import AIDevTeam
    team = AIDevTeam(enable_memory=False)
    if not team.agents:
        print(f"  {Colors.RED}No agents available.{Colors.RESET}\n")
        return

    _result = await run_single_task(team, prompt, "quick")
    print()
