"""Async httpx wrapper around TaxJar v2 API."""
from typing import Optional

import httpx

from src.apps.tax.schemas import TaxRateResponse


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

    async def get_rate(
        self,
        zip: str,
        city: Optional[str] = None,
        state: Optional[str] = None,
        country: str = "US",
    ) -> TaxRateResponse:
        params: dict = {"country": country}
        if city:
            params["city"] = city
        if state:
            params["state"] = state
        async with httpx.AsyncClient() as client:
            resp = await client.get(
                f"{self._base_url}/rates/{zip}",
                params=params,
                headers=self._headers,
                timeout=10.0,
            )
            resp.raise_for_status()
        d = resp.json()["rate"]
        combined = float(d.get("combined_rate", 0))
        city_name = d.get("city", "")
        state_name = d.get("state", "")
        label = f"{d.get('zip', zip)} — {city_name}, {state_name} ({combined * 100:.2f}%)"
        return TaxRateResponse(
            zip=d.get("zip", zip),
            city=d.get("city"),
            state=d.get("state"),
            country=d.get("country", country),
            combined_rate=combined,
            state_rate=float(d.get("state_rate", 0)),
            county_rate=float(d.get("county_rate", 0)),
            city_rate=float(d.get("city_rate", 0)),
            special_district_rate=float(d.get("special_district_rate", 0)),
            label=label,
        )
