"""HTTP client for sending requests to the embedded API server (TReq)."""
from __future__ import annotations

import requests


class TgrezliRequestError(Exception):
    """Raised when a TReq request fails (network or HTTP error)."""


class TReq:
    """Fluent client for POST requests to the TgrEzLi API server."""

    def __init__(self, endpoint: str, host: str = "localhost", port: int = 9999, timeout_sec: float = 30.0) -> None:
        self.endpoint = endpoint if endpoint.startswith("/") else f"/{endpoint}"
        self._host = host
        self._port = port
        self._timeout = timeout_sec
        self._body: dict = {}

    def host(self, host: str) -> TReq:
        self._host = host
        return self

    def port(self, port: int) -> TReq:
        self._port = port
        return self

    def timeout(self, seconds: float) -> TReq:
        self._timeout = seconds
        return self

    def arg(self, name: str, value: object) -> TReq:
        self._body[name] = value
        return self

    def body(self, body_dict: dict) -> TReq:
        self._body = dict(body_dict)
        return self

    def send(self) -> requests.Response:
        url = f"http://{self._host}:{self._port}{self.endpoint}"
        try:
            return requests.post(url, json=self._body, timeout=self._timeout)
        except requests.RequestException as e:
            raise TgrezliRequestError(f"Request to {url} failed: {e}") from e


__all__ = ["TReq", "TgrezliRequestError"]
