"""HTTP client for talking to the Dobby daemon REST API."""
from __future__ import annotations

import aiohttp


class DobbyClient:
    """Async HTTP client that communicates with the Dobby daemon."""

    def __init__(self, base_url: str = "http://127.0.0.1:8420"):
        self.base_url = base_url.rstrip("/")

    async def get(self, path: str, params: dict | None = None) -> dict | list:
        """Send a GET request and return parsed JSON."""
        url = f"{self.base_url}{path}"
        try:
            async with aiohttp.ClientSession() as session, session.get(url, params=params) as resp:
                resp.raise_for_status()
                return await resp.json()
        except aiohttp.ClientConnectionError:
            print("Dobby daemon not running. Start with: dobby start")
            raise

    async def post(self, path: str, json: dict | None = None, params: dict | None = None) -> dict:
        """Send a POST request and return parsed JSON."""
        url = f"{self.base_url}{path}"
        try:
            async with aiohttp.ClientSession() as session, \
                    session.post(url, json=json, params=params) as resp:
                resp.raise_for_status()
                return await resp.json()
        except aiohttp.ClientConnectionError:
            print("Dobby daemon not running. Start with: dobby start")
            raise

    async def patch(self, path: str, json: dict | None = None) -> dict:
        """Send a PATCH request and return parsed JSON."""
        url = f"{self.base_url}{path}"
        try:
            async with aiohttp.ClientSession() as session, session.patch(url, json=json) as resp:
                resp.raise_for_status()
                return await resp.json()
        except aiohttp.ClientConnectionError:
            print("Dobby daemon not running. Start with: dobby start")
            raise

    async def delete(self, path: str) -> dict:
        """Send a DELETE request and return parsed JSON."""
        url = f"{self.base_url}{path}"
        try:
            async with aiohttp.ClientSession() as session, session.delete(url) as resp:
                resp.raise_for_status()
                return await resp.json()
        except aiohttp.ClientConnectionError:
            print("Dobby daemon not running. Start with: dobby start")
            raise
