"""EmbiPay Agent API client."""

from typing import Optional

from .admin import EmbiPayAdmin  # reuse _request pattern


class EmbiPayAgent:
    """
    Client for EmbiPay Agent API.
    Requires base_url and agent_key (Bearer).
    """

    def __init__(self, base_url: str, agent_key: str):
        self.base_url = base_url.rstrip("/")
        self.agent_key = agent_key
        self._headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {agent_key}",
        }

    def _request(self, method: str, path: str, body: Optional[dict] = None):
        import urllib.request
        import urllib.error
        import json

        url = f"{self.base_url}{path}"
        data = json.dumps(body).encode() if body else None
        req = urllib.request.Request(url, data=data, headers=self._headers, method=method)
        try:
            with urllib.request.urlopen(req) as resp:
                return json.loads(resp.read().decode())
        except urllib.error.HTTPError as e:
            err_body = e.read().decode() if e.fp else "{}"
            try:
                data = json.loads(err_body)
            except json.JSONDecodeError:
                data = {"error": err_body}
            raise Exception(data.get("error", data.get("details", str(e)))) from e

    def fetch_tasks(self):
        return self._request("GET", "/api/agent/fetch-tasks")

    def complete_task(self, task_id: int, status: str = "completed", note: Optional[str] = None):
        return self._request("POST", "/api/agent/complete-task", {
            "task_id": task_id,
            "status": status,
            "note": note,
        })

    def send_invitation(self, human_email: str):
        return self._request("POST", "/api/agent/send-invitation", {"human_email": human_email})

    def get_tasks(self):
        return self._request("GET", "/api/agent/tasks")
