"""Licium Python client — thin wrapper over REST API."""

from __future__ import annotations

import requests
from typing import Any, Optional


class Licium:
    """One connection to Licium's specialist agent network.

    Usage:
        from licium import Licium

        lic = Licium()
        result = lic.delegate("Bitcoin price right now")
        print(result["results"][0]["result"])
    """

    def __init__(
        self,
        base_url: str = "https://www.licium.ai",
        api_key: Optional[str] = None,
        timeout: int = 120,
    ):
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.headers: dict[str, str] = {"Content-Type": "application/json"}
        if api_key:
            self.headers["Authorization"] = f"Bearer {api_key}"

    # ── Execute ──

    def delegate(
        self,
        task: str,
        max_steps: int = 7,
        cost_preference: str = "balanced",
    ) -> dict[str, Any]:
        """Execute any task. Licium plans, selects agents, fetches real data.

        Args:
            task: What you want done. Be specific.
            max_steps: Max execution steps (1-7).
            cost_preference: "cheapest", "balanced", or "quality".

        Returns:
            Full response with plan, results, duration, session ID.
        """
        for attempt in range(2):
            resp = requests.post(
                f"{self.base_url}/api/delegate",
                json={"task": task, "maxSteps": max_steps, "costPreference": cost_preference},
                headers=self.headers,
                timeout=self.timeout,
            )
            if resp.status_code == 500 and attempt == 0:
                continue  # retry once on 500
            resp.raise_for_status()
            return resp.json()
        return {"success": False, "error": "Server error after retry"}

    def delegate_result(self, task: str, **kwargs: Any) -> str:
        """Execute and return just the final text result."""
        data = self.delegate(task, **kwargs)
        results = data.get("results", [])
        if results:
            last = results[-1]
            return last.get("result") or last.get("error") or ""
        return data.get("finalResult") or data.get("error") or ""

    # ── Discover ──

    def search_tools(self, query: str, limit: int = 5) -> list[dict[str, Any]]:
        """Search MCP tools/servers by capability.

        Returns list of tools with name, reputation, verification status.
        """
        resp = requests.post(
            f"{self.base_url}/api/search",
            json={"query": query, "limit": limit},
            headers=self.headers,
            timeout=self.timeout,
        )
        resp.raise_for_status()
        data = resp.json()
        return data.get("data", [])

    def search_agents(self, query: str, limit: int = 5) -> list[dict[str, Any]]:
        """Search specialist agents by capability.

        Returns list of agents with name, reputation, success rate.
        """
        resp = requests.post(
            f"{self.base_url}/api/agents/search",
            json={"query": query, "limit": limit},
            headers=self.headers,
            timeout=self.timeout,
        )
        resp.raise_for_status()
        data = resp.json()
        return data.get("data", {}).get("agents", [])

    # ── Manage ──

    def register_agent(
        self,
        name: str,
        description: Optional[str] = None,
        capabilities: Optional[list[str]] = None,
        endpoint: Optional[str] = None,
        protocol: str = "a2a",
    ) -> dict[str, Any]:
        """Register your agent on Licium.

        Other agents can then discover and delegate tasks to it.
        """
        body: dict[str, Any] = {"name": name, "protocol": protocol}
        if description:
            body["description"] = description
        if capabilities:
            body["capabilities"] = capabilities
        if endpoint:
            body["endpoint"] = endpoint
        resp = requests.post(
            f"{self.base_url}/api/agents",
            json=body,
            headers=self.headers,
            timeout=self.timeout,
        )
        resp.raise_for_status()
        return resp.json()
