"""AUTX API response types."""

from dataclasses import asdict, dataclass, field
from typing import Any


@dataclass
class ProxyResponse:
    """Response from a proxy request."""
    content: bytes
    status_code: int
    content_type: str
    headers: dict[str, str] = field(default_factory=dict)
    request_id: str = ""
    latency_ms: int = 0
    agent_ticker: str = ""

    @property
    def text(self) -> str:
        return self.content.decode("utf-8", errors="replace")

    @property
    def json(self) -> Any:
        import json
        return json.loads(self.content)


@dataclass
class OrderResponse:
    """Response from creating an order."""
    id: str
    agent_id: str
    status: str
    amount_paid: float
    platform_fee: float
    created_at: str


@dataclass
class OrderResult:
    """Result of a completed order."""
    id: str
    status: str
    output_hash: str | None = None
    output_text: str | None = None
    completed_at: str | None = None


# --- Agent Manifest ---

@dataclass
class ManifestInput:
    """Agent manifest input configuration."""
    type: str = "text"
    accepts_files: bool = False
    file_types: list[str] = field(default_factory=list)
    max_size_bytes: int = 10_485_760

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)


@dataclass
class ManifestOutput:
    """Agent manifest output configuration."""
    type: str = "json"
    produces_files: bool = False
    content_types: list[str] = field(default_factory=lambda: ["application/json"])
    max_size_bytes: int = 52_428_800

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)


@dataclass
class AgentManifest:
    """Agent capability manifest."""
    input: ManifestInput = field(default_factory=ManifestInput)
    output: ManifestOutput = field(default_factory=ManifestOutput)

    def to_dict(self) -> dict[str, Any]:
        return {"input": self.input.to_dict(), "output": self.output.to_dict()}


# --- Agent Profile ---

@dataclass
class AgentProfileData:
    """Agent profile for marketplace listing."""
    tagline: str
    capabilities: list[str] = field(default_factory=list)
    use_cases: list[str] = field(default_factory=list)
    output_description: str | None = None
    best_for: str | None = None
    limitations: str | None = None

    def to_dict(self) -> dict[str, Any]:
        return {k: v for k, v in asdict(self).items() if v is not None}


# --- Agent Responses ---

@dataclass
class AgentResponse:
    """Full agent response from create operations (includes endpoint_url)."""
    id: str
    owner_id: str | None
    name: str
    ticker: str
    endpoint_url: str
    description: str | None
    category: str | None
    service_price: float
    auth_tier: str
    provider: str | None
    provider_key_configured: bool
    status: str
    uptime_pct: float
    success_rate: float
    total_revenue: float
    total_requests: int
    created_at: str
    contract_address: str | None = None
    dividend_splitter_address: str | None = None
    agent_token_address: str | None = None
    manifest: dict[str, Any] | None = None
    profile: dict[str, Any] | None = None


@dataclass
class AgentListItem:
    """Public agent view (no endpoint_url)."""
    id: str
    owner_id: str | None
    name: str
    ticker: str
    description: str | None
    category: str | None
    service_price: float
    auth_tier: str
    provider: str | None
    provider_key_configured: bool
    status: str
    uptime_pct: float
    success_rate: float
    total_revenue: float
    total_requests: int
    created_at: str
    contract_address: str | None = None
    dividend_splitter_address: str | None = None
    agent_token_address: str | None = None
    manifest: dict[str, Any] | None = None
    profile: dict[str, Any] | None = None


# --- Parsers ---

def _parse_agent_response(data: dict[str, Any]) -> AgentResponse:
    return AgentResponse(
        id=str(data["id"]),
        owner_id=str(data["owner_id"]) if data.get("owner_id") else None,
        name=data["name"],
        ticker=data["ticker"],
        endpoint_url=data["endpoint_url"],
        description=data.get("description"),
        category=data.get("category"),
        service_price=float(data["service_price"]),
        auth_tier=data["auth_tier"],
        provider=data.get("provider"),
        provider_key_configured=data.get("provider_key_configured", False),
        status=data["status"],
        uptime_pct=float(data.get("uptime_pct", 0)),
        success_rate=float(data.get("success_rate", 0)),
        total_revenue=float(data.get("total_revenue", 0)),
        total_requests=data.get("total_requests", 0),
        created_at=str(data["created_at"]),
        contract_address=data.get("contract_address"),
        dividend_splitter_address=data.get("dividend_splitter_address"),
        agent_token_address=data.get("agent_token_address"),
        manifest=data.get("manifest"),
        profile=data.get("profile"),
    )


def _parse_agent_list_item(data: dict[str, Any]) -> AgentListItem:
    return AgentListItem(
        id=str(data["id"]),
        owner_id=str(data["owner_id"]) if data.get("owner_id") else None,
        name=data["name"],
        ticker=data["ticker"],
        description=data.get("description"),
        category=data.get("category"),
        service_price=float(data["service_price"]),
        auth_tier=data["auth_tier"],
        provider=data.get("provider"),
        provider_key_configured=data.get("provider_key_configured", False),
        status=data["status"],
        uptime_pct=float(data.get("uptime_pct", 0)),
        success_rate=float(data.get("success_rate", 0)),
        total_revenue=float(data.get("total_revenue", 0)),
        total_requests=data.get("total_requests", 0),
        created_at=str(data["created_at"]),
        contract_address=data.get("contract_address"),
        dividend_splitter_address=data.get("dividend_splitter_address"),
        agent_token_address=data.get("agent_token_address"),
        manifest=data.get("manifest"),
        profile=data.get("profile"),
    )
