"""Schemas for AI provider credential CRUD endpoints."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID

from sqlmodel import SQLModel

RUNTIME_ANNOTATION_TYPES = (datetime, UUID)


class ProviderCredentialCreate(SQLModel):
    provider: str
    account_key: str
    display_name: str = ""
    api_key: str | None = None
    base_url: str | None = None
    active: bool = True


class ProviderCredentialUpdate(SQLModel):
    display_name: str | None = None
    api_key: str | None = None       # None = keep existing; "" = clear it
    base_url: str | None = None
    active: bool | None = None


class TokenWindowRead(SQLModel):
    limit: int | None = None
    remaining: int | None = None
    used: int | None = None
    pct_used: float | None = None
    reset_at: str | None = None      # ISO 8601 UTC
    reset_in_ms: int | None = None   # ms until reset


class RequestWindowRead(SQLModel):
    limit: int | None = None
    remaining: int | None = None
    reset_at: str | None = None
    reset_in_ms: int | None = None


class ProviderUsageLiveRead(SQLModel):
    """Real-time token usage and rate limit data fetched directly from the provider API."""

    provider: str
    account_key: str
    checked_at: str           # ISO 8601 UTC
    reachable: bool
    error: str | None = None
    tokens: TokenWindowRead
    input_tokens: TokenWindowRead   # Anthropic splits input tokens separately
    requests: RequestWindowRead
    models: list[str] = []


class ProviderCredentialRead(SQLModel):
    """Safe read schema — api_key is never included."""

    id: UUID
    organization_id: UUID
    provider: str
    account_key: str
    display_name: str
    api_key_last_four: str | None
    has_api_key: bool
    base_url: str | None
    active: bool
    created_at: datetime
    updated_at: datetime
