import enum
from datetime import datetime

from sqlalchemy import Boolean, DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import BaseModel


class CloudServerType(str, enum.Enum):
    """对接的上游云系统类型。当前只支持魔方云。"""

    DCIMCLOUD = "dcimcloud"
    ZJMF_FINANCE = "zjmf_finance"


class CloudAccountType(str, enum.Enum):
    """魔方云账号身份。

    - admin：自营管理员，登录 /v1/login?a=a，拥有镜像/区域目录等完整权限
    - agent：资源池代理商，登录 /token，开通时需要 rid 资源包
    """

    ADMIN = "admin"
    AGENT = "agent"
    CLIENT = "client"
    RESOURCE = "resource"


class CloudServerStatus(str, enum.Enum):
    UNKNOWN = "unknown"
    ONLINE = "online"
    OFFLINE = "offline"


class CloudServer(BaseModel):
    """对接的上游云服务器实例（目前仅魔方云）。"""

    __tablename__ = "cloud_servers"

    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="展示名")
    server_type: Mapped[CloudServerType] = mapped_column(
        String(32), default=CloudServerType.DCIMCLOUD.value, nullable=False, index=True
    )
    account_type: Mapped[CloudAccountType] = mapped_column(
        String(16), default=CloudAccountType.ADMIN.value, nullable=False
    )

    hostname: Mapped[str] = mapped_column(String(255), nullable=False, comment="域名/IP，不含 schema")
    port: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="0=按 secure 默认")
    secure: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False, comment="是否 https")

    username: Mapped[str] = mapped_column(String(100), nullable=False)
    password_encrypted: Mapped[str] = mapped_column(Text, nullable=False, comment="AES-GCM 密文")

    user_prefix: Mapped[str | None] = mapped_column(
        String(64), nullable=True, comment="开通云账号时拼到 username 前面（多租户隔离）"
    )

    disabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)

    status: Mapped[CloudServerStatus] = mapped_column(
        String(16), default=CloudServerStatus.UNKNOWN.value, nullable=False, index=True
    )
    last_check_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    last_check_message: Mapped[str | None] = mapped_column(String(500), nullable=True)

    client_id: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="魔方云客户ID，开通实例时传 client 字段")

    remark: Mapped[str | None] = mapped_column(Text, nullable=True)
    sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    @property
    def base_url(self) -> str:
        scheme = "https" if self.secure else "http"
        if self.port and self.port not in (80, 443):
            return f"{scheme}://{self.hostname}:{self.port}"
        return f"{scheme}://{self.hostname}"
