"""Read one fictional inventory record using an injected HTTP client."""
import asyncio
import re

import httpx
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from typing import Literal

ID_PATTERN = r"^[A-Z]{2,8}-[1-9][0-9]{0,5}$"
API_ROOT = "https://inventory.example.invalid/v1/"
HTTP_TIMEOUT = httpx.Timeout(5.0, connect=2.0, pool=1.0)


class Artifact(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid")
    item_id: str = Field(pattern=ID_PATTERN)
    title: str = Field(min_length=1, max_length=80)
    status: Literal["ready", "maintenance"]


class AdapterError(Exception):
    """A stable public error without response bodies, URLs or credentials."""

    def __init__(self, code: str, message: str):
        self.code = code
        super().__init__(f"{code}: {message}")


class ArtifactClient:
    def __init__(self, http: httpx.AsyncClient, token: str | None = None, deadline: float = 8.0):
        if not 0 < deadline <= 60:
            raise ValueError("deadline must be between 0 and 60 seconds")
        self._http = http
        self._token = token
        self._deadline = deadline

    async def get_artifact(self, item_id: str) -> Artifact:
        """Validate the identifier, read once and return an explicit output model."""
        if not isinstance(item_id, str) or re.fullmatch(ID_PATTERN, item_id) is None:
            raise AdapterError("INVALID_ID", "Expected an identifier such as KIT-42")
        headers = {"Authorization": f"Bearer {self._token}"} if self._token else {}
        try:
            async with asyncio.timeout(self._deadline):
                response = await self._http.get(
                    API_ROOT + "items/" + item_id,
                    headers=headers,
                    timeout=HTTP_TIMEOUT,
                    follow_redirects=False,
                )
        except (TimeoutError, httpx.TimeoutException):
            raise AdapterError("TIMEOUT", "The inventory did not answer in time") from None
        except httpx.RequestError:
            raise AdapterError("NETWORK", "The inventory connection failed") from None
        status = response.status_code
        if status in (401, 403):
            raise AdapterError("AUTH", "Check inventory access outside the tool")
        if status == 404:
            raise AdapterError("NOT_FOUND", "No record with this identifier")
        if status == 429:
            raise AdapterError("RATE_LIMIT", "Request limit reached; do not retry in a loop")
        if status >= 500:
            raise AdapterError("UPSTREAM", "The inventory is temporarily unavailable")
        if status != 200:
            raise AdapterError("HTTP_STATUS", "Unexpected inventory response")
        try:
            result = Artifact.model_validate(response.json())
        except (ValueError, ValidationError):
            raise AdapterError("BAD_RESPONSE", "The inventory response has the wrong shape") from None
        if result.item_id != item_id:
            raise AdapterError("BAD_RESPONSE", "The inventory returned a different identifier")
        return result
