from datetime import datetime
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

from app.core.card_key_types import CARD_TYPE_DURATION, CARD_TYPE_POINTS

CardKeyType = Literal["时长", "点数"]


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

    id: int
    serial_number: str
    card_type: CardKeyType
    duration_days: int
    points_amount: float | None = None
    created_at: datetime
    activated_at: datetime | None = None
    user_id: int | None = None
    username: str | None = None
    oem_id: int | None = None
    agent_id: int | None = None
    remark: str | None = None
    oem_remark: str | None = None
    agent_remark: str | None = None


class CardKeyCreate(BaseModel):
    card_type: CardKeyType = Field(default=CARD_TYPE_DURATION, description="卡密类型")
    duration_days: int | None = Field(
        default=None, ge=1, le=3650, description="时长卡有效天数"
    )
    points_amount: float | None = Field(
        default=None, gt=0, description="点数卡点数面值"
    )
    remark: str | None = Field(default=None, max_length=255)
    count: int = Field(default=1, ge=1, le=100, description="批量生成数量")
    serial_number: str | None = Field(default=None, max_length=64)
    oem_id: int | None = Field(default=None, description="预分配给 OEM")
    agent_id: int | None = Field(default=None, description="预分配给代理")

    @field_validator("remark")
    @classmethod
    def normalize_remark(cls, value: str | None) -> str | None:
        if value is None:
            return None
        stripped = value.strip()
        return stripped or None

    @field_validator("serial_number")
    @classmethod
    def normalize_serial(cls, value: str | None) -> str | None:
        if value is None:
            return None
        stripped = value.strip().upper()
        return stripped or None

    @model_validator(mode="after")
    def validate_type_and_value(self) -> "CardKeyCreate":
        if self.serial_number and self.count != 1:
            raise ValueError("指定序列号时仅可生成 1 张卡密")
        if self.oem_id is not None and self.agent_id is not None:
            raise ValueError("OEM 与代理只能指定其一")
        if self.card_type == CARD_TYPE_DURATION:
            if self.duration_days is None:
                raise ValueError("时长卡密须填写有效天数")
        elif self.card_type == CARD_TYPE_POINTS:
            if self.points_amount is None:
                raise ValueError("点数卡密须填写点数")
        return self


class CardKeyUpdate(BaseModel):
    card_type: CardKeyType | None = None
    duration_days: int | None = Field(default=None, ge=1, le=3650)
    points_amount: float | None = Field(default=None, gt=0)
    remark: str | None = Field(default=None, max_length=255)

    @field_validator("remark")
    @classmethod
    def normalize_remark(cls, value: str | None) -> str | None:
        if value is None:
            return None
        stripped = value.strip()
        return stripped or None

    @model_validator(mode="after")
    def validate_type_and_value(self) -> "CardKeyUpdate":
        if self.card_type == CARD_TYPE_DURATION and self.points_amount is not None:
            raise ValueError("时长卡密不能设置点数")
        if self.card_type == CARD_TYPE_POINTS and self.duration_days is not None:
            raise ValueError("点数卡密不能设置有效天数")
        return self


class CardKeyBatchCreateResult(BaseModel):
    items: list[CardKeyOut]
    created_count: int
