"""Pydantic models for the Agntor SDK."""

from __future__ import annotations

from enum import Enum
from typing import Any, Optional

from pydantic import BaseModel, Field


class AgntorError(Exception):
    """Raised when an Agntor API call fails."""

    def __init__(self, message: str, code: str = "UNKNOWN", status_code: int | None = None):
        super().__init__(message)
        self.code = code
        self.status_code = status_code


class Tier(str, Enum):
    BRONZE = "Bronze"
    SILVER = "Silver"
    GOLD = "Gold"
    PLATINUM = "Platinum"


# ── Config ────────────────────────────────────────────────────────────────────

class AgntorConfig(BaseModel):
    """Configuration for the Agntor client."""
    api_key: str
    agent_id: str
    chain: str = "base"
    base_url: str = "https://app.agntor.com"
    timeout: float = 30.0
    max_retries: int = 3


# ── Identity ──────────────────────────────────────────────────────────────────

class AgentIdentity(BaseModel):
    id: str
    name: str
    organization: str | None = None
    version: str | None = None
    trust_score: int = 0
    audit_level: str = "Bronze"
    is_claimed: bool = False
    wallet_address: str | None = None
    metadata: dict[str, Any] | None = None
    created_at: str | None = None
    updated_at: str | None = None


# ── Trust ─────────────────────────────────────────────────────────────────────

class PillarScore(BaseModel):
    score: int
    max: int
    details: dict[str, Any] = Field(default_factory=dict)


class TrustBreakdown(BaseModel):
    identity: PillarScore
    safety: PillarScore
    reliability: PillarScore
    transactions: PillarScore
    age: PillarScore


class TrustScore(BaseModel):
    score: int
    tier: str
    breakdown: TrustBreakdown | None = None


# ── Verification ──────────────────────────────────────────────────────────────

class ProbeResult(BaseModel):
    challenge: str | None = None
    category: str | None = None
    passed: bool
    confidence: float
    response_time: int = 0


class VerificationResult(BaseModel):
    agent_id: str
    probe_score: int
    probes_run: int
    probes_passed: int
    endpoint_reachable: bool
    details: list[ProbeResult] = Field(default_factory=list)
    trust: TrustScore | None = None


# ── Escrow ────────────────────────────────────────────────────────────────────

class EscrowRecord(BaseModel):
    id: str
    agent_id: str | None = None
    worker_wallet: str | None = None
    amount: int | None = None
    status: str = "pending"
    task_description: str | None = None
    settled_at: str | None = None
    resolved_by: str | None = None
    created_at: str | None = None


class SettlementResult(BaseModel):
    task_id: str
    previous_status: str
    new_status: str
    settled_at: str
    resolved_by: str | None = None
    reason: str | None = None
    trust: dict[str, Any] | None = None


# ── Audit ─────────────────────────────────────────────────────────────────────

class AuditLogEntry(BaseModel):
    id: int | None = None
    agent_id: str | None = None
    action: str
    resource: str | None = None
    cost: float = 0.0
    success: bool = True
    timestamp: str | None = None
    details: dict[str, Any] | None = None


# ── Health ────────────────────────────────────────────────────────────────────

class HealthMetric(BaseModel):
    id: int | None = None
    agent_id: str | None = None
    uptime_percentage: float | None = None
    error_rate: float | None = None
    avg_latency_ms: int | None = None
    recorded_at: str | None = None


# ── Guard / Redact ────────────────────────────────────────────────────────────

class GuardResult(BaseModel):
    classification: str  # "pass" | "block"
    violation_types: list[str] = Field(default_factory=list)
    reasoning: str | None = None


class RedactFinding(BaseModel):
    type: str
    span: tuple[int, int]
    value: str | None = None


class RedactResult(BaseModel):
    redacted: str
    findings: list[RedactFinding] = Field(default_factory=list)
