import requests


class ReachlyClient:
    def __init__(self, api_key, base_url="http://localhost:3000"):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")

    def _post(self, path, payload):
        response = requests.post(
            f"{self.base_url}{path}",
            json=payload,
            headers={
                "x-api-key": self.api_key,
                "Content-Type": "application/json",
            },
            timeout=20,
        )
        data = response.json()
        if not response.ok or data.get("ok") is False:
            raise RuntimeError(data.get("error") or "Reachly API request failed")
        return data

    def send_otp(self, to, code, ttl_minutes=10):
        return self._post("/api/public/otp", {
            "to": to,
            "code": str(code),
            "ttlMinutes": ttl_minutes,
        })

    def send_message(self, to, text):
        return self._post("/api/public/messages", {
            "to": to,
            "text": text,
        })
