from __future__ import annotations

import os
import typing as t
import requests


class YeomenClient:
    def __init__(self, base_url: str | None = None, api_key: str | None = None, timeout_s: int = 60):
        self.base_url = (base_url or os.getenv("YEOMEN_BASE_URL", "")).rstrip("/")
        self.api_key = api_key or os.getenv("YEOMEN_API_KEY", "")
        self.timeout_s = timeout_s

        if not self.base_url:
            raise ValueError("Missing YEOMEN_BASE_URL")
        if not self.api_key:
            raise ValueError("Missing YEOMEN_API_KEY")

    def _headers(self) -> dict[str, str]:
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

    def propose_intent(
        self,
        intent: str,
        chain_hint: str | None = None,
        wallet_hint: str | None = None,
        webhook_url: str | None = None,
    ) -> dict[str, t.Any]:
        payload: dict[str, t.Any] = {
            "intent": intent,
            "context": {},
        }
        if chain_hint:
            payload["context"]["chain_hint"] = chain_hint
        if wallet_hint:
            payload["context"]["wallet_hint"] = wallet_hint
        if webhook_url:
            payload["webhook_url"] = webhook_url

        r = requests.post(
            f"{self.base_url}/v1/intents",
            headers=self._headers(),
            json=payload,
            timeout=self.timeout_s,
        )
        r.raise_for_status()
        return r.json()

    def approve_intent(self, intent_id: str, approval_note: str = "User approved") -> dict[str, t.Any]:
        payload = {"approved": True, "approval_note": approval_note}
        r = requests.post(
            f"{self.base_url}/v1/intents/{intent_id}/approve",
            headers=self._headers(),
            json=payload,
            timeout=self.timeout_s,
        )
        r.raise_for_status()
        return r.json()

    def execute(self, execution_id: str) -> dict[str, t.Any]:
        payload = {"confirm_execute": True}
        r = requests.post(
            f"{self.base_url}/v1/executions/{execution_id}/execute",
            headers=self._headers(),
            json=payload,
            timeout=self.timeout_s,
        )
        r.raise_for_status()
        return r.json()
