"""
title: Zeldoc.ai Web Search
description: Search the web through Zeldoc.ai's private search endpoint.
version: 1.0.0
"""

import json
import urllib.request
from typing import Optional

from pydantic import BaseModel, Field

SEARCH_URL = "https://api.zeldoc.ai/v1/search/zeldoc-search"
MAX_RESULTS = 10


class Tools:
    class Valves(BaseModel):
        ZELDOC_API_KEY: str = Field(default="", description="Your Zeldoc.ai API key")

    def __init__(self):
        self.valves = self.Valves()

    def search_web(
        self,
        query: str,
        time_range: Optional[str] = None,
        language: Optional[str] = None,
    ) -> str:
        """
        Search the web through Zeldoc.ai's private search. Returns titles,
        URLs and snippets.
        :param query: The search query.
        :param time_range: Optional. Only results from this period: day, week, month or year.
        :param language: Optional. Two-letter language code, e.g. en, de, da.
        """
        if not self.valves.ZELDOC_API_KEY:
            return "Zeldoc.ai API key is not set. Open the tool's valves and add it."

        body = {"query": query}
        if time_range:
            body["time_range"] = time_range
        if language:
            body["language"] = language

        request = urllib.request.Request(
            SEARCH_URL,
            data=json.dumps(body).encode(),
            headers={
                "Authorization": f"Bearer {self.valves.ZELDOC_API_KEY}",
                "Content-Type": "application/json",
                # Cloudflare rejects the default Python user agent.
                "User-Agent": "open-webui-zeldoc-search/1.0",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                results = json.load(response).get("results", [])
        except Exception as error:  # noqa: BLE001
            return f"Zeldoc.ai search failed: {error}"

        if not results:
            return "No results found."

        lines = []
        for index, result in enumerate(results[:MAX_RESULTS], start=1):
            lines.append(f"--- Result {index} ---")
            lines.append(f"Title: {result.get('title', '')}")
            lines.append(f"Link: {result.get('url', '')}")
            if result.get("date"):
                lines.append(f"Date: {result['date']}")
            lines.append(f"Snippet: {result.get('snippet', '')}")
            lines.append("")
        return "\n".join(lines).strip()
