import enum

from sqlalchemy import Boolean, ForeignKey, Integer, Numeric, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.models.base import BaseModel


class ProductStatus(str, enum.Enum):
    DRAFT = "draft"  # 草稿，不展示
    ACTIVE = "active"  # 在售
    HIDDEN = "hidden"  # 隐藏，老用户可见
    DEPRECATED = "deprecated"  # 停售，不可再购，老订单照旧


class ProductType(str, enum.Enum):
    """产品形态。决定下单流程与开通方式。"""

    SERVER = "server"  # 云服务器/VPS/独立服务器
    HOSTING = "hosting"  # 虚拟主机
    DOMAIN = "domain"  # 域名注册
    SSL = "ssl"  # SSL 证书
    LICENSE = "license"  # 软件授权
    OTHER = "other"


class StockPolicy(str, enum.Enum):
    UNLIMITED = "unlimited"
    TRACKED = "tracked"  # 走 stock 字段


class ProductApiType(str, enum.Enum):
    """产品与上游云接口的对接方式。

    - none: 无对接（域名/SSL/纯展示），下单后人工或第三方流程开通
    - dcim_cloud_image: 走 cloud_server (account_type=admin)，api_identifier 存镜像 id
    - dcim_cloud_rid: 走 cloud_server (account_type=agent)，api_identifier 存资源包 rid
    """

    NONE = "none"
    DCIM_CLOUD_IMAGE = "dcim_cloud_image"
    DCIM_CLOUD_RID = "dcim_cloud_rid"
    ZJMF_FINANCE = "zjmf_finance"
    PLUGIN = "plugin"


class Product(BaseModel):
    """具体可售产品。一个产品 = 一个固定规格 SKU。

    自定义字段、配置选项、价格都挂在它身上。
    """

    __tablename__ = "products"

    group_id: Mapped[int] = mapped_column(
        ForeignKey("product_groups.id", ondelete="CASCADE"), nullable=False, index=True
    )
    sku: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
    name: Mapped[str] = mapped_column(String(150), nullable=False)

    type: Mapped[ProductType] = mapped_column(
        String(16), default=ProductType.SERVER.value, nullable=False, index=True
    )
    status: Mapped[ProductStatus] = mapped_column(
        String(16), default=ProductStatus.DRAFT.value, nullable=False, index=True
    )

    # 规格摘要（用于卡片快速展示）
    # CPU 拆成结构化四列：vCPU 数 / 型号 / 主频 / 睿频（MHz，避免存浮点）
    vcpu: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="vCPU 核心数")
    cpu_model: Mapped[str | None] = mapped_column(
        String(64), nullable=True, comment="处理器型号，如 Xeon E5-2680 v4"
    )
    cpu_base_mhz: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="基础主频 MHz，展示时 ÷1000 → GHz"
    )
    cpu_turbo_mhz: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="睿频 MHz，展示时 ÷1000 → GHz"
    )
    memory: Mapped[str | None] = mapped_column(String(64), nullable=True)
    disk: Mapped[str | None] = mapped_column(String(64), nullable=True)
    bandwidth: Mapped[str | None] = mapped_column(String(64), nullable=True)

    # 高亮特性列表，JSON 数组 [{"icon":"shield","text":"DDoS 防护"}]
    features: Mapped[str | None] = mapped_column(Text, nullable=True)
    # 卡片上显示的标签 ["热卖","新品"]
    badges: Mapped[str | None] = mapped_column(Text, nullable=True)

    # 价格基线（元）。实际下单价由 pricing 周期 + 配置选项加价计算。
    base_setup_fee: Mapped[float] = mapped_column(Numeric(10, 2), default=0, nullable=False, comment="一次性安装费(元)")
    base_price: Mapped[float] = mapped_column(Numeric(10, 2), default=0, nullable=False, comment="基础月价(元)，用于卡片展示")

    # 库存
    stock_policy: Mapped[StockPolicy] = mapped_column(
        String(16), default=StockPolicy.UNLIMITED.value, nullable=False
    )
    stock: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="tracked 时生效")

    # 限购：0=不限
    min_quantity: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    max_quantity: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="0=不限")

    # 是否启用自动开通；off 时下单后人工审核
    auto_provision: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    # 是否允许试用
    trial_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    trial_days: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    is_featured: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    requires_real_name: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)

    cloud_server_id: Mapped[int | None] = mapped_column(
        ForeignKey("cloud_servers.id", ondelete="SET NULL"), nullable=True, index=True
    )
    api_type: Mapped[ProductApiType] = mapped_column(
        String(32), default=ProductApiType.NONE.value, nullable=False
    )
    api_identifier: Mapped[str | None] = mapped_column(
        String(128), nullable=True, comment="上游标识：image id / rid 等，按 api_type 解释"
    )
    provision_interface_id: Mapped[int | None] = mapped_column(
        ForeignKey("provision_interfaces.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
        comment="插件开通接口配置 ID",
    )
    provision_config: Mapped[list | None] = mapped_column(
        JSON, nullable=True, comment="产品配置字段列表 [ConfigField]"
    )
