from __future__ import annotations

from enum import Enum
from typing import Any, Optional

from pydantic import BaseModel, Field, field_validator


class Network(str, Enum):
    mainnet = "mainnet"
    testnet = "testnet"


class ContractViewRequest(BaseModel):
    method: str = Field(min_length=1, max_length=256)
    args: dict[str, Any] = Field(default_factory=dict)
    network: Network = Network.mainnet
    finality: str = Field(default="final", pattern="^(final|optimistic)$")


class ContractViewResponse(BaseModel):
    block_height: Optional[int] = None
    block_hash: Optional[str] = None
    logs: list[str] = Field(default_factory=list)
    raw_result: Optional[list[int]] = None
    decoded_result: Any = None


class NetworkInfo(BaseModel):
    network: Network
    rpc_url: str


class ErrorResponse(BaseModel):
    error: str
    details: Optional[dict[str, Any]] = None


_ACCOUNT_ID_RE = r"^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$|^[a-f0-9]{64}$"


class AccountPath(BaseModel):
    account_id: str

    @field_validator("account_id")
    @classmethod
    def validate_account_id(cls, value: str) -> str:
        import re

        if not re.fullmatch(_ACCOUNT_ID_RE, value):
            raise ValueError("Invalid NEAR account_id format")
        if len(value) < 2 or len(value) > 64:
            raise ValueError("account_id must be between 2 and 64 chars")
        return value
