"""Tools the GAIA agent can call.

Every tool is a plain Python function plus a short description and an argument
schema. The descriptions are rendered into the system prompt, so adding a tool
here is enough to make it usable by the agent.

All tools are deliberately defensive: a failure returns a readable error string
instead of raising, because a weak model still has to keep going.
"""

from __future__ import annotations

import csv
import io
import json
import os
import re
import subprocess
import sys
import threading
from dataclasses import dataclass, field
from pathlib import Path

import requests
from bs4 import BeautifulSoup

USER_AGENT = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/131.0 Safari/537.36"
)
HTTP = requests.Session()
HTTP.headers.update({"User-Agent": USER_AGENT})

MAX_OBSERVATION = 6000  # characters fed back to the model per tool call


def _clip(text: str, limit: int = MAX_OBSERVATION) -> str:
    text = re.sub(r"\n{3,}", "\n\n", text or "").strip()
    if len(text) <= limit:
        return text
    return text[: limit - 200].rstrip() + "\n... [truncated]"


# --------------------------------------------------------------------------- #
# Context shared by the tools of a single task
# --------------------------------------------------------------------------- #
@dataclass
class TaskContext:
    task_id: str
    question: str
    file_name: str = ""
    workdir: Path = field(default_factory=Path.cwd)
    artifact: Path | None = None
    cache: dict = field(default_factory=dict)

    @property
    def artifact_suffix(self) -> str:
        return (self.artifact.suffix.lower() if self.artifact else Path(self.file_name).suffix.lower())


# --------------------------------------------------------------------------- #
# Web tools
# --------------------------------------------------------------------------- #
def _decode_ddg_href(href: str) -> str:
    match = re.search(r"uddg=([^&]+)", href or "")
    if match:
        from urllib.parse import unquote

        return unquote(match.group(1))
    return href


def web_search(query: str, max_results: int = 8) -> str:
    """Search the web and return titles, URLs and snippets."""
    query = (query or "").strip()
    if not query:
        return "Error: empty query."

    results: list[str] = []
    try:
        response = HTTP.get(
            "https://html.duckduckgo.com/html/", params={"q": query}, timeout=25
        )
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "lxml")
            for block in soup.select("div.result")[:max_results]:
                link = block.select_one("a.result__a")
                if not link:
                    continue
                snippet = block.select_one("a.result__snippet") or block.select_one("div.result__snippet")
                title = link.get_text(" ", strip=True)
                url = _decode_ddg_href(link.get("href", ""))
                body = snippet.get_text(" ", strip=True) if snippet else ""
                results.append(f"{len(results) + 1}. {title}\n   URL: {url}\n   {body}")
    except Exception as exc:
        results.append(f"(duckduckgo failed: {exc})")

    if not results:
        try:  # single fallback engine, keeps the tool useful when DDG throttles us
            response = HTTP.get("https://www.mojeek.com/search", params={"q": query}, timeout=25)
            soup = BeautifulSoup(response.text, "lxml")
            for item in soup.select("li:has(a.title), ul.results-standard li")[:max_results]:
                link = item.select_one("a")
                if not link or not link.get("href", "").startswith("http"):
                    continue
                text = item.get_text(" ", strip=True)
                results.append(f"{len(results) + 1}. {link.get_text(' ', strip=True)}\n   URL: {link['href']}\n   {text[:300]}")
        except Exception as exc:
            results.append(f"(mojeek failed: {exc})")

    if not results:
        return f"No search results found for: {query}"
    return _clip("\n".join(results))


def _html_to_text(html: str) -> str:
    soup = BeautifulSoup(html, "lxml")
    for tag in soup(["script", "style", "noscript", "svg", "header", "footer", "nav", "form"]):
        tag.decompose()
    title = soup.title.get_text(" ", strip=True) if soup.title else ""
    main = soup.select_one("main, article, #content, #mw-content-text, .post-content") or soup.body or soup
    text = main.get_text("\n", strip=True)
    return (f"{title}\n\n{text}" if title else text).strip()


def visit_page(url: str) -> str:
    """Download a page (or PDF) and return its readable text."""
    url = (url or "").strip()
    if not url.startswith("http"):
        return f"Error: '{url}' is not a valid URL."
    try:
        response = HTTP.get(url, timeout=30, allow_redirects=True)
    except Exception as exc:
        return f"Error fetching {url}: {exc}"
    if response.status_code >= 400:
        return f"Error: HTTP {response.status_code} for {url}"

    content_type = response.headers.get("content-type", "")
    if "pdf" in content_type or url.lower().endswith(".pdf"):
        try:
            from pypdf import PdfReader

            reader = PdfReader(io.BytesIO(response.content))
            text = "\n".join((page.extract_text() or "") for page in reader.pages[:30])
            return _clip(text) or "The PDF had no extractable text."
        except Exception as exc:
            return f"Error reading PDF: {exc}"

    if "html" not in content_type and "text" not in content_type:
        return f"Skipped {url}: unsupported content type '{content_type}' (size {len(response.content)} bytes)."
    return _clip(_html_to_text(response.text))


def _wikipedia_search(query: str, limit: int = 5) -> list[str]:
    response = HTTP.get(
        "https://en.wikipedia.org/w/api.php",
        params={"action": "query", "list": "search", "srsearch": query, "srlimit": limit, "format": "json"},
        timeout=25,
    )
    hits = (response.json().get("query") or {}).get("search") or []
    return [hit["title"] for hit in hits]


def _wikipedia_text(title: str) -> str:
    response = HTTP.get(
        "https://en.wikipedia.org/w/api.php",
        params={
            "action": "query",
            "prop": "extracts",
            "explaintext": 1,
            "exlimit": "max",
            "titles": title,
            "format": "json",
            "redirects": 1,
        },
        timeout=30,
    )
    for page in ((response.json().get("query") or {}).get("pages") or {}).values():
        if page.get("extract"):
            return page["extract"]
    return ""


def _split_sections(text: str) -> list[tuple[str, str]]:
    """Split a Wikipedia plaintext extract into (heading, body) pairs."""
    sections: list[tuple[str, str]] = []
    heading = "Introduction"
    buffer: list[str] = []
    for line in text.splitlines():
        stripped = line.strip()
        if stripped.startswith("==") and stripped.endswith("=="):
            sections.append((heading, "\n".join(buffer).strip()))
            heading = stripped.strip("= ").strip()
            buffer = []
        else:
            buffer.append(line)
    sections.append((heading, "\n".join(buffer).strip()))
    return [(name, body) for name, body in sections if name or body]


def _table_to_text(table) -> str:
    """Render an HTML table as pipe separated rows so lists survive text extraction."""
    rows = []
    for row in table.find_all("tr"):
        cells = [cell.get_text(" ", strip=True) for cell in row.find_all(["th", "td"])]
        cells = [cell for cell in cells if cell]
        if cells:
            rows.append(" | ".join(cells))
    return "\n".join(rows)


def _render_node(node) -> str:
    if node.name == "table":
        return _table_to_text(node)
    for table in node.find_all("table"):
        table.replace_with(_table_to_text(table))
    return node.get_text("\n", strip=True)


def _wikipedia_html_sections(title: str) -> list[tuple[str, str]]:
    """Fetch the rendered article and split it into sections, keeping tables."""
    response = HTTP.get(
        "https://en.wikipedia.org/w/api.php",
        params={"action": "parse", "page": title, "prop": "text", "format": "json", "redirects": 1},
        timeout=30,
    )
    html = ((response.json().get("parse") or {}).get("text") or {}).get("*")
    if not html:
        return []
    soup = BeautifulSoup(html, "lxml")
    container = soup.select_one(".mw-parser-output") or soup
    sections: list[tuple[str, str]] = []
    heading = "Introduction"
    buffer: list[str] = []
    for child in container.find_all(recursive=False):
        heading_node = child if child.name in {"h2", "h3", "h4", "h5"} else None
        if heading_node is None and child.name == "div":
            # Current Wikipedia markup wraps every heading in <div class="mw-heading">.
            inner = child.select_one("h2, h3, h4, h5")
            if inner is not None and len(child.get_text(strip=True)) < 120:
                heading_node = inner
        if heading_node is not None:
            sections.append((heading, "\n".join(buffer).strip()))
            heading = heading_node.get_text(" ", strip=True)
            buffer = []
        elif child.name in {"p", "ul", "ol", "dl", "table", "blockquote", "pre", "div", "figure"}:
            rendered = _render_node(child)
            if rendered:
                buffer.append(rendered)
    sections.append((heading, "\n".join(buffer).strip()))
    return [(name, body) for name, body in sections if name or body]


def _wikipedia_sections(title: str) -> list[tuple[str, str]]:
    """Prefer the rendered HTML (it contains tables); fall back to plain text."""
    try:
        sections = _wikipedia_html_sections(title)
        if sections and sum(len(body) for _, body in sections) > 500:
            return sections
    except Exception:
        pass
    try:
        return _split_sections(_wikipedia_text(title))
    except Exception:
        return []


STOPWORDS = {
    "the", "and", "for", "with", "from", "that", "this", "what", "which", "who", "whom",
    "how", "many", "much", "was", "were", "are", "has", "have", "had", "did", "does",
    "their", "there", "about", "into", "give", "list", "between", "version", "english",
    "wikipedia", "page", "use", "using", "can", "you", "only", "answer", "question",
}


def wikipedia(query: str, limit: int = 2500) -> str:
    """Read English Wikipedia: search titles, then return the most relevant sections."""
    query = (query or "").strip()
    if not query:
        return "Error: empty query."
    try:
        titles = _wikipedia_search(query)
    except Exception as exc:
        return f"Wikipedia search failed: {exc}"
    if not titles:
        return f"No Wikipedia page found for: {query}"

    title = titles[0]
    try:
        sections = _wikipedia_sections(title)
    except Exception as exc:
        return f"Wikipedia page fetch failed: {exc}"
    if not sections:
        return f"Wikipedia matches for {query}: {', '.join(titles)} (but no text could be extracted)."

    keywords = [
        word
        for word in re.findall(r"[a-z]{3,}", query.lower())
        if word not in STOPWORDS
    ]

    def score(section: tuple[str, str]) -> int:
        heading, body = section
        lowered = body.lower()
        # A keyword in the heading is a much stronger signal than in the body,
        # otherwise long biography sections would always win over "Studio albums".
        heading_hits = sum(1 for keyword in keywords if keyword in heading.lower())
        distinct_hits = sum(1 for keyword in keywords if keyword in lowered)
        return 10 * heading_hits + 3 * distinct_hits

    ranked = sorted(sections, key=score, reverse=True)
    chosen: list[tuple[str, str]] = []

    def add(section: tuple[str, str], index: int) -> None:
        if section not in chosen:
            chosen.append(section)
        # A short section is usually a container such as "Discography"; keep the
        # subsection that follows it in document order.
        if len(section[1]) < 500 and index + 1 < len(sections):
            follower = sections[index + 1]
            if follower not in chosen:
                chosen.append(follower)

    if sections:
        chosen.append(sections[0])
    for section in ranked[:2]:
        add(section, sections.index(section))
        if len(chosen) >= 3:
            break

    parts = [f"# {title}", f"Other matches: {', '.join(titles[1:])}" if len(titles) > 1 else ""]
    parts.append("Sections: " + " | ".join(name for name, _ in sections[:40]))
    for heading, body in chosen[:4]:
        if body:
            parts.append(f"## {heading}\n{body[:limit]}")
    return _clip("\n".join(part for part in parts if part), 7000)


def youtube_transcript(url: str) -> str:
    """Return the English transcript of a YouTube video when captions exist."""
    match = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url or "")
    if not match:
        return f"Error: could not find a video id in '{url}'."
    video_id = match.group(1)
    try:
        from youtube_transcript_api import YouTubeTranscriptApi

        api = YouTubeTranscriptApi()
        fetched = api.fetch(video_id, languages=["en", "en-US", "en-GB"])
        text = " ".join(segment.text for segment in fetched)
        return _clip(text) or "Empty transcript."
    except Exception as exc:
        return (
            f"Could not load a transcript for video {video_id}: {type(exc).__name__}: {exc}. "
            "The video may have no captions; consider searching the web for a description instead."
        )


# --------------------------------------------------------------------------- #
# Local tools
# --------------------------------------------------------------------------- #
def run_python(code: str, ctx: TaskContext) -> str:
    """Execute Python in a subprocess and return stdout/stderr."""
    code = (code or "").strip()
    if not code:
        return "Error: empty code."
    if "```" in code:  # strip markdown fences if the model added them
        code = re.sub(r"```(?:python)?", "", code).strip()
    env = {**os.environ, "PYTHONIOENCODING": "utf-8"}
    try:
        completed = subprocess.run(
            [sys.executable, "-c", code],
            cwd=str(ctx.workdir),
            capture_output=True,
            text=True,
            timeout=90,
            env=env,
        )
    except subprocess.TimeoutExpired:
        return "Error: the code timed out after 90 seconds."
    except Exception as exc:
        return f"Error running code: {exc}"
    output = (completed.stdout or "") + (("\n[stderr]\n" + completed.stderr) if completed.stderr else "")
    if not output.strip():
        output = "(no output)"
    return _clip(output, 3000)


def _render_table(path: Path, limit_rows: int = 400) -> str:
    try:
        import openpyxl

        workbook = openpyxl.load_workbook(path, data_only=True)
    except Exception as exc:
        return f"Error opening spreadsheet: {exc}"

    parts = []
    for sheet in workbook.worksheets:
        rows = list(sheet.iter_rows(values_only=True))
        buffer = io.StringIO()
        writer = csv.writer(buffer)
        for row in rows[:limit_rows]:
            writer.writerow(["" if cell is None else cell for cell in row])
        note = "" if len(rows) <= limit_rows else f"\n[only the first {limit_rows} of {len(rows)} rows shown]"
        parts.append(f"### Sheet: {sheet.title} ({len(rows)} rows)\n{buffer.getvalue().strip()}{note}")
    return _clip("\n\n".join(parts))


def read_attachment(ctx: TaskContext) -> str:
    """Return the text content of the file attached to the current question."""
    if not ctx.artifact or not ctx.artifact.exists():
        return "This question has no attached file."
    path = ctx.artifact
    suffix = path.suffix.lower()

    if suffix in {".xlsx", ".xlsm"}:
        return _render_table(path)
    if suffix == ".csv":
        return _clip(path.read_text(errors="replace"))
    if suffix in {".py", ".txt", ".md", ".json", ".html", ".xml", ".yaml", ".yml", ".ini", ".log"}:
        return _clip(path.read_text(errors="replace"))
    if suffix == ".pdf":
        try:
            from pypdf import PdfReader

            reader = PdfReader(str(path))
            return _clip("\n".join((page.extract_text() or "") for page in reader.pages[:40]))
        except Exception as exc:
            return f"Error reading PDF: {exc}"
    if suffix == ".docx":
        try:
            import docx

            document = docx.Document(str(path))
            return _clip("\n".join(paragraph.text for paragraph in document.paragraphs))
        except Exception as exc:
            return f"Error reading DOCX: {exc}"
    if suffix in {".mp3", ".wav", ".m4a", ".flac", ".ogg"}:
        return "This is an audio file; use the transcribe_audio tool to read it."
    if suffix in {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}:
        return "This is an image; use the look_at_image tool to inspect it."
    return f"Unsupported file type '{suffix}'. The file is available at {path} for the python tool."


_WHISPER = {}
_WHISPER_LOCK = threading.Lock()


def _load_audio(path: Path):
    """Decode any audio file to 16 kHz mono float32, without needing ffmpeg."""
    import numpy as np

    try:
        import miniaudio

        decoded = miniaudio.decode_file(
            str(path),
            output_format=miniaudio.SampleFormat.SIGNED16,
            nchannels=1,
            sample_rate=16000,
        )
        return np.frombuffer(decoded.samples, dtype=np.int16).astype(np.float32) / 32768.0
    except Exception:
        import soundfile as sf

        data, rate = sf.read(str(path), dtype="float32", always_2d=True)
        mono = data.mean(axis=1)
        if rate != 16000:
            target = int(len(mono) * 16000 / rate)
            mono = np.interp(np.linspace(0, len(mono) - 1, target), np.arange(len(mono)), mono).astype(np.float32)
        return mono


def transcribe_audio(ctx: TaskContext, question: str = "") -> str:
    """Transcribe the attached audio file to text."""
    if not ctx.artifact or not ctx.artifact.exists():
        return "This question has no audio file."
    if "transcript" in ctx.cache:
        return ctx.cache["transcript"]

    text = ""
    with _WHISPER_LOCK:
        try:
            import mlx_whisper

            audio = _load_audio(ctx.artifact)
            if "model" not in _WHISPER:
                _WHISPER["model"] = os.getenv("GAIA_WHISPER_MODEL", "mlx-community/whisper-large-v3-turbo")
            result = mlx_whisper.transcribe(audio, path_or_hf_repo=_WHISPER["model"])
            text = result.get("text", "")
        except Exception as mlx_error:
            try:  # portable fallback
                from faster_whisper import WhisperModel

                model = _WHISPER.setdefault("faster", WhisperModel("base", device="cpu", compute_type="int8"))
                segments, _ = model.transcribe(str(ctx.artifact))
                text = " ".join(segment.text for segment in segments)
            except Exception as exc:
                return f"Transcription is unavailable ({mlx_error} / {exc})."

    text = (text or "").strip()
    ctx.cache["transcript"] = _clip(text, 4000)
    return ctx.cache["transcript"] or "The transcription came back empty."


_VLM_LOCK = threading.Lock()


def _run_vision_worker(image: Path, question: str, timeout: int = 900) -> str:
    """Answer one question about an image in a throwaway process.

    The 8B text model is resident while a task runs, so loading the 7B vision
    model in the same process exhausts unified memory. The worker loads, answers
    and exits, and the memory comes back.
    """
    root = Path(__file__).resolve().parent.parent
    env = dict(os.environ)
    env.setdefault("TOKENIZERS_PARALLELISM", "false")
    completed = subprocess.run(
        [
            sys.executable,
            "-m",
            "gaia_agent.vlm_worker",
            "--image",
            str(image),
            "--question",
            question,
            "--max-tokens",
            "400",
        ],
        cwd=str(root),
        env=env,
        capture_output=True,
        text=True,
        timeout=timeout,
    )
    if completed.returncode != 0:
        detail = (completed.stderr or "").strip().splitlines()
        raise RuntimeError(detail[-1] if detail else f"vision worker exited {completed.returncode}")
    return (completed.stdout or "").strip()


def look_at_image(ctx: TaskContext, question: str) -> str:
    """Describe or answer a question about the attached image."""
    if not ctx.artifact or not ctx.artifact.exists():
        return "This question has no image file."
    question = (question or ctx.question).strip()
    cache_key = f"image::{question}"
    if cache_key in ctx.cache:
        return ctx.cache[cache_key]

    with _VLM_LOCK:
        try:
            text = _run_vision_worker(ctx.artifact, question)
            ctx.cache[cache_key] = _clip(text, 3000)
            return ctx.cache[cache_key]
        except Exception as local_error:
            base_url = os.getenv("OPENAI_BASE_URL")
            api_key = os.getenv("OPENAI_API_KEY")
            if base_url and api_key:
                try:
                    import base64

                    from openai import OpenAI

                    encoded = base64.b64encode(ctx.artifact.read_bytes()).decode()
                    client = OpenAI(base_url=base_url, api_key=api_key, timeout=120)
                    response = client.chat.completions.create(
                        model=os.getenv("GAIA_VLM_MODEL", "gpt-4o-mini"),
                        messages=[
                            {
                                "role": "user",
                                "content": [
                                    {"type": "text", "text": question},
                                    {
                                        "type": "image_url",
                                        "image_url": {"url": f"data:image/png;base64,{encoded}"},
                                    },
                                ],
                            }
                        ],
                        max_tokens=400,
                    )
                    return _clip((response.choices[0].message.content or "").strip(), 3000)
                except Exception as exc:
                    return f"Image inspection failed ({local_error} / {exc})."
            return f"Image inspection is unavailable: {local_error}"


# --------------------------------------------------------------------------- #
# Registry
# --------------------------------------------------------------------------- #
@dataclass
class Tool:
    name: str
    description: str
    signature: str
    run: object

    def render(self) -> str:
        return f"- {self.name}{self.signature}: {self.description}"


def build_registry(ctx: TaskContext) -> dict[str, Tool]:
    """Create the tool table for one task (some tools only make sense with a file)."""
    tools = [
        Tool(
            "web_search",
            "Search the web (DuckDuckGo). Returns numbered results with titles, URLs and snippets.",
            "(query)",
            lambda query: web_search(query),
        ),
        Tool(
            "visit_page",
            "Open a URL and return its readable text (HTML or PDF). Use it on the most promising search result.",
            "(url)",
            lambda url: visit_page(url),
        ),
        Tool(
            "wikipedia",
            "Search English Wikipedia and return the most relevant sections of the best matching article. "
            "Best source for names, dates, discographies and lists.",
            "(query)",
            lambda query: wikipedia(query),
        ),
        Tool(
            "python",
            "Run Python code and return stdout. Use it for arithmetic, parsing and any computation.",
            "(code)",
            lambda code: run_python(code, ctx),
        ),
        Tool(
            "youtube_transcript",
            "Fetch the English captions of a YouTube video.",
            "(url)",
            lambda url: youtube_transcript(url),
        ),
    ]

    if ctx.artifact:
        tools.append(
            Tool(
                "read_attachment",
                f"Read the file attached to this question ({ctx.file_name}). Call it without arguments.",
                "()",
                lambda **_: read_attachment(ctx),
            )
        )
        if ctx.artifact_suffix in {".mp3", ".wav", ".m4a", ".flac", ".ogg"}:
            tools.append(
                Tool(
                    "transcribe_audio",
                    "Transcribe the attached audio file to text. Call it without arguments.",
                    "()",
                    lambda **_: transcribe_audio(ctx),
                )
            )
        if ctx.artifact_suffix in {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}:
            tools.append(
                Tool(
                    "look_at_image",
                    "Ask a vision model a question about the attached image, e.g. 'Write the board position as a FEN'.",
                    "(question)",
                    lambda question: look_at_image(ctx, question),
                )
            )
    else:
        tools.append(
            Tool(
                "read_attachment",
                "Read the file attached to this question. (No file is attached to this one.)",
                "()",
                lambda **_: read_attachment(ctx),
            )
        )
    return {tool.name: tool for tool in tools}


def execute(tool: Tool, arguments: dict) -> str:
    """Run a tool, converting every failure into a readable observation."""
    try:
        if isinstance(arguments, dict):
            return tool.run(**arguments)
        if arguments is None:
            return tool.run()
        return tool.run(arguments)
    except TypeError as exc:
        return f"Error: wrong arguments for {tool.name} ({exc}). Expected {tool.name}{tool.signature}."
    except Exception as exc:
        return f"Error while running {tool.name}: {type(exc).__name__}: {exc}"


def render_tool_list(registry: dict[str, Tool]) -> str:
    return "\n".join(tool.render() for tool in registry.values())


def parse_tool_input(raw) -> dict:
    """Normalise the many shapes a weak model produces for tool arguments."""
    if isinstance(raw, dict):
        return raw
    if raw in (None, "", "null"):
        return {}
    if isinstance(raw, str):
        stripped = raw.strip()
        if stripped.startswith("{"):
            try:
                return json.loads(stripped)
            except json.JSONDecodeError:
                pass
        return {"input": stripped}
    return {"input": raw}
