from datetime import datetime
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field


CloudServerTypeLiteral = Literal["dcimcloud", "zjmf_finance"]
CloudAccountTypeLiteral = Literal["admin", "agent", "client", "resource"]


class CloudServerCreate(BaseModel):
    name: str = Field(..., min_length=1, max_length=100)
    server_type: CloudServerTypeLiteral = "dcimcloud"
    account_type: CloudAccountTypeLiteral = "admin"
    hostname: str = Field(..., min_length=1, max_length=255)
    port: int = Field(0, ge=0, le=65535)
    secure: bool = True
    username: str = Field(..., min_length=1, max_length=100)
    password: str = Field(..., min_length=1, max_length=255)
    client_id: int | None = None
    user_prefix: str | None = Field(None, max_length=64)
    disabled: bool = False
    remark: str | None = None
    sort_order: int = 0


class CloudServerUpdate(BaseModel):
    name: str | None = Field(None, min_length=1, max_length=100)
    server_type: CloudServerTypeLiteral | None = None
    account_type: CloudAccountTypeLiteral | None = None
    hostname: str | None = Field(None, min_length=1, max_length=255)
    port: int | None = Field(None, ge=0, le=65535)
    secure: bool | None = None
    username: str | None = Field(None, min_length=1, max_length=100)
    password: str | None = Field(None, min_length=1, max_length=255)
    client_id: int | None = None
    user_prefix: str | None = Field(None, max_length=64)
    disabled: bool | None = None
    remark: str | None = None
    sort_order: int | None = None


class CloudServerResponse(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    name: str
    server_type: str
    account_type: str
    hostname: str
    port: int
    secure: bool
    username: str
    client_id: int | None
    user_prefix: str | None
    disabled: bool
    status: str
    last_check_at: datetime | None
    last_check_message: str | None
    remark: str | None
    sort_order: int
    created_at: datetime
    updated_at: datetime


class CloudServerTestRequest(BaseModel):
    """用于添加表单中的"测试"按钮（连接尚未保存的凭据）。"""

    server_type: CloudServerTypeLiteral = "dcimcloud"
    account_type: CloudAccountTypeLiteral = "admin"
    hostname: str = Field(..., min_length=1, max_length=255)
    port: int = Field(0, ge=0, le=65535)
    secure: bool = True
    username: str = Field(..., min_length=1, max_length=100)
    password: str = Field(..., min_length=1, max_length=255)


class CloudServerTestResult(BaseModel):
    ok: bool
    message: str
    latency_ms: int | None = None
