from datetime import datetime
from typing import Literal

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


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

    id: int
    serial_number: str
    duration_days: int
    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


class CardKeyCreate(BaseModel):
    duration_days: int = Field(ge=1, le=3650, 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 serial_only_for_single(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 与代理只能指定其一")
        return self


class CardKeyUpdate(BaseModel):
    duration_days: int | None = Field(default=None, ge=1, le=3650)
    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


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