from __future__ import annotations

from datetime import datetime
from typing import Literal

from pydantic import BaseModel, Field

from app.schemas.common import ORMModel


class AdminLoginRequest(BaseModel):
    username: str = Field(min_length=1, max_length=50)
    password: str = Field(min_length=1, max_length=100)


class AdminLoginResponse(BaseModel):
    token: str
    expiredAt: datetime
    admin: dict


class AdminRead(ORMModel):
    id: int
    username: str
    name: str
    status: int
    isSuperAdmin: bool = False
    mustChangePassword: bool = False
    permissions: list[str] = Field(default_factory=list)


class ManagedAdminCreateRequest(BaseModel):
    username: str = Field(min_length=3, max_length=50, pattern=r"^[A-Za-z0-9_.-]+$")
    name: str = Field(min_length=1, max_length=50)
    initialPassword: str = Field(min_length=8, max_length=100)
    status: int = Field(default=1, ge=0, le=1)
    permissions: list[str] = Field(default_factory=list, max_length=100)


class ManagedAdminUpdateRequest(BaseModel):
    name: str = Field(min_length=1, max_length=50)
    status: int = Field(default=1, ge=0, le=1)
    permissions: list[str] = Field(default_factory=list, max_length=100)
    resetPassword: str | None = Field(default=None, min_length=8, max_length=100)


class AdminPasswordChangeRequest(BaseModel):
    currentPassword: str = Field(min_length=1, max_length=100)
    newPassword: str = Field(min_length=8, max_length=100)


class CostBreakdownItem(BaseModel):
    scene: str
    modelName: str
    requestCount: int
    inputToken: int
    outputToken: int
    totalToken: int
    estimatedCost: float
    currency: str | None = None


class DashboardStats(BaseModel):
    userCount: int
    sessionCount: int
    messageCount: int
    aiRequestCount: int
    knowledgeCount: int
    inputToken: int
    outputToken: int
    totalToken: int
    estimatedCost: float | None = None
    costCurrency: str | None = None
    costBreakdown: list[CostBreakdownItem] = Field(default_factory=list)


class AdminUserUpdateRequest(BaseModel):
    status: int | None = Field(default=None, ge=0, le=1)
    dailyChatLimit: int | None = Field(default=None, ge=0, le=100000)
    expiredAt: datetime | None = None
    entitlementPlanId: int | None = Field(default=None, gt=0)
    entitlementExpiredAt: datetime | None = None
    entitlementRemark: str | None = Field(default=None, max_length=255)


class AdminUserCreateRequest(BaseModel):
    phone: str = Field(min_length=11, max_length=20)
    name: str = Field(min_length=1, max_length=50)
    nickname: str | None = Field(default=None, max_length=50)
    status: int = Field(default=1, ge=0, le=1)
    dailyChatLimit: int | None = Field(default=None, ge=0, le=100000)
    expiredAt: datetime | None = None


class AdminUserImportItem(BaseModel):
    phone: str = Field(default="", max_length=20)
    name: str = Field(default="", max_length=50)
    nickname: str | None = Field(default=None, max_length=50)
    status: int = Field(default=1, ge=0, le=1)
    dailyChatLimit: int | None = Field(default=None, ge=0, le=100000)
    expiredAt: datetime | None = None


class AdminUserImportRequest(BaseModel):
    students: list[AdminUserImportItem] = Field(default_factory=list)


class EntitlementPlanSaveRequest(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    planType: Literal["basic", "deep", "addon"] = "basic"
    description: str | None = Field(default=None, max_length=255)
    validityDays: int | None = Field(default=None, ge=1, le=3650)
    monthlyTopicLimit: int | None = Field(default=None, ge=0, le=100000)
    enableGrowthProfile: int = Field(default=0, ge=0, le=1)
    enablePeriodicReports: int = Field(default=0, ge=0, le=1)
    allowHelpCard: int = Field(default=1, ge=0, le=1)
    allowShareDraft: int = Field(default=1, ge=0, le=1)
    deductQuota: int = Field(default=1, ge=0, le=1)
    status: int = Field(default=1, ge=0, le=1)
    sortOrder: int = Field(default=0, ge=0, le=100000)


class UserEntitlementAssignRequest(BaseModel):
    planId: int = Field(gt=0)
    effectiveAt: datetime | None = None
    expiredAt: datetime | None = None
    remark: str | None = Field(default=None, max_length=255)


class UserEntitlementRenewRequest(BaseModel):
    extensionDays: int = Field(ge=1, le=3650)
    idempotencyKey: str = Field(min_length=8, max_length=100)
    remark: str | None = Field(default=None, max_length=255)


class UserEntitlementBatchRenewRequest(UserEntitlementRenewRequest):
    userIds: list[int] = Field(min_length=1, max_length=200)


class KnowledgeSaveRequest(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    feishuSpaceId: str = Field(min_length=1, max_length=100)
    feishuNodeId: str = Field(min_length=1, max_length=100)
    status: int = Field(default=1, ge=0, le=1)
    remark: str | None = Field(default=None, max_length=255)
    knowledgeType: str = Field(default="general", pattern="^(course|qa|general|fixed)$")


class PromptSaveRequest(BaseModel):
    promptContent: str = Field(min_length=1)


class ContentGenerationConfigSaveRequest(BaseModel):
    templateContent: str = Field(min_length=1, max_length=20000)
    instructionContent: str = Field(min_length=1, max_length=10000)


class ContentGenerationPreviewRequest(BaseModel):
    configType: Literal["help_card", "share_draft"]
    templateContent: str = Field(min_length=1, max_length=20000)


class ContentGenerationTestRequest(ContentGenerationPreviewRequest):
    instructionContent: str = Field(min_length=1, max_length=10000)
    sampleText: str = Field(min_length=1, max_length=20000)


class AgentDebugHistoryMessage(BaseModel):
    role: Literal["user", "assistant"]
    content: str = Field(min_length=1, max_length=20000)


class AgentDebugRequest(BaseModel):
    promptContent: str = Field(min_length=1)
    modelId: int = Field(gt=0)
    userId: int | None = Field(default=None, gt=0)
    topicSessionId: int | None = Field(default=None, gt=0)
    knowledgeIds: list[int] = Field(default_factory=list)
    knowledgeVersions: dict[int, int] = Field(default_factory=dict)
    question: str = Field(min_length=1, max_length=2000)
    history: list[AgentDebugHistoryMessage] = Field(default_factory=list, max_length=100)
    temperature: float | None = Field(default=None, ge=0, le=2)
    topP: float | None = Field(default=None, ge=0, le=1)
    topK: int | None = Field(default=None, ge=1, le=1000)
    presencePenalty: float | None = Field(default=None, ge=-2, le=2)
    frequencyPenalty: float | None = Field(default=None, ge=-2, le=2)
    maxToken: int | None = Field(default=8192, ge=1, le=100000)
    streamEnabled: int = Field(default=1, ge=0, le=1)
    reasoningVisible: int = Field(default=0, ge=0, le=1)
    responseDepth: int = Field(default=35, ge=0, le=100)


class AgentRuntimeConfigSaveRequest(BaseModel):
    temperature: float | None = Field(default=None, ge=0, le=2)
    topP: float | None = Field(default=None, ge=0, le=1)
    topK: int | None = Field(default=None, ge=1, le=1000)
    presencePenalty: float | None = Field(default=None, ge=-2, le=2)
    frequencyPenalty: float | None = Field(default=None, ge=-2, le=2)
    maxToken: int = Field(default=8192, ge=256, le=100000)
    streamEnabled: int = Field(default=1, ge=0, le=1)
    reasoningVisible: int = Field(default=0, ge=0, le=1)
    responseDepth: int = Field(default=35, ge=0, le=100)


class ModelSaveRequest(BaseModel):
    provider: str = Field(min_length=1, max_length=50)
    displayName: str | None = Field(default=None, max_length=100)
    apiType: str = Field(default="openai_compatible", max_length=50)
    modelName: str = Field(min_length=1, max_length=100)
    baseUrl: str | None = Field(default=None, max_length=255)
    apiUrl: str = Field(default="", max_length=255)
    apiKey: str = ""
    authType: str = Field(default="bearer", max_length=30)
    apiVersion: str | None = Field(default=None, max_length=50)
    temperature: float | None = Field(default=0.2, ge=0, le=2)
    topP: float | None = Field(default=None, ge=0, le=1)
    topK: int | None = Field(default=None, ge=1, le=1000)
    presencePenalty: float | None = Field(default=None, ge=-2, le=2)
    frequencyPenalty: float | None = Field(default=None, ge=-2, le=2)
    maxToken: int | None = Field(default=1024, ge=1, le=100000)
    contextWindow: int | None = Field(default=None, ge=1, le=2000000)
    streamEnabled: int = Field(default=1, ge=0, le=1)
    responseFormat: str | None = Field(default=None, max_length=50)
    extraParams: str | None = None
    remark: str | None = Field(default=None, max_length=255)
    timeoutSecond: int = Field(default=30, ge=1, le=300)
    inputPricePer1k: float | None = Field(default=None, ge=0, le=1000000)
    outputPricePer1k: float | None = Field(default=None, ge=0, le=1000000)
    currency: str = Field(default="CNY", max_length=10)
    usageScenarios: str | None = Field(default=None, max_length=255)
    allowSummary: int = Field(default=1, ge=0, le=1)
    allowReport: int = Field(default=1, ge=0, le=1)
    allowFixedInfo: int = Field(default=1, ge=0, le=1)
    allowSimpleKnowledge: int = Field(default=1, ge=0, le=1)
    allowDeepChat: int = Field(default=1, ge=0, le=1)


class EnableModelRequest(BaseModel):
    modelId: int
    enabled: int = Field(default=1, ge=0, le=1)


class DefaultModelRequest(BaseModel):
    modelId: int


class SystemConfigSaveRequest(BaseModel):
    configKey: str = Field(min_length=1, max_length=100)
    configValue: str
    description: str | None = Field(default=None, max_length=255)
