"""
Admin API Schemas

Request/response models for the admin API endpoints.
"""

from typing import List, Optional, Dict, Any, Literal
from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime


# ============================================================================
# Dashboard Schemas
# ============================================================================

class DashboardStatsResponse(BaseModel):
    """Dashboard statistics response"""
    total_users: int = Field(..., description="Total number of users")
    total_projects: int = Field(..., description="Total number of projects")
    total_tasks: int = Field(..., description="Total number of tasks")
    active_tasks: int = Field(..., description="Number of active tasks")
    pending_tasks: int = Field(..., description="Number of pending tasks")
    failed_tasks: int = Field(..., description="Number of failed tasks")
    completed_tasks: int = Field(..., description="Number of completed tasks")


class SystemResourceInfo(BaseModel):
    """System resource information"""
    cpu_usage: float = Field(..., description="CPU usage percentage")
    memory_usage: float = Field(..., description="Memory usage percentage")
    disk_usage: float = Field(..., description="Disk usage percentage")
    uptime: float = Field(..., description="System uptime in seconds")


class DashboardSystemResponse(BaseModel):
    """Dashboard system resources response"""
    resources: SystemResourceInfo
    timestamp: str = Field(default_factory=lambda: datetime.now().isoformat())


class ActivityItem(BaseModel):
    """Activity log item"""
    id: str
    type: str = Field(..., description="Activity type: user, project, task, etc.")
    action: str = Field(..., description="Action performed")
    user_id: Optional[str] = Field(None, description="User who performed the action")
    user_name: Optional[str] = Field(None, description="Username")
    target_id: Optional[str] = Field(None, description="Target entity ID")
    target_type: Optional[str] = Field(None, description="Target entity type")
    details: Optional[Dict[str, Any]] = Field(None, description="Additional details")
    created_at: str = Field(..., description="Activity timestamp")


class DashboardActivityResponse(BaseModel):
    """Dashboard recent activity response"""
    items: List[ActivityItem]
    total: int


# ============================================================================
# User Management Schemas
# ============================================================================

class AdminUserListItem(BaseModel):
    """User list item for admin"""
    id: str
    username: str
    email: Optional[str]
    is_active: bool
    is_superuser: bool
    permissions: List[str]
    roles: List[str]
    avatar_url: Optional[str]
    created_at: str  # ISO format string
    last_login: Optional[str]  # ISO format string


class AdminUserListResponse(BaseModel):
    """User list response for admin"""
    items: List[AdminUserListItem]
    total: int
    page: int
    page_size: int
    total_pages: int


class AdminUserFilter(BaseModel):
    """User filter parameters"""
    is_active: Optional[bool] = None
    is_superuser: Optional[bool] = None
    role: Optional[str] = None
    search: Optional[str] = Field(None, description="Search by username or email")


class AdminUserCreateRequest(BaseModel):
    """Create user request for admin"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    email: str = Field(..., description="邮箱")
    password: str = Field(..., min_length=6, description="密码")
    is_active: bool = Field(default=True, description="是否激活")
    is_superuser: bool = Field(default=False, description="是否超级用户")
    roles: List[str] = Field(default=[], description="用户角色")
    permissions: List[str] = Field(default=[], description="用户权限")


class AdminUserUpdateRequest(BaseModel):
    """Update user request for admin"""
    email: Optional[str] = None
    is_active: Optional[bool] = None
    is_superuser: Optional[bool] = None
    permissions: Optional[List[str]] = None
    roles: Optional[List[str]] = None


class AdminUserToggleActiveRequest(BaseModel):
    """Toggle user active status"""
    is_active: bool


class AdminUserToggleActiveResponse(BaseModel):
    """Toggle user active status response"""
    id: str
    is_active: bool
    message: str


class AdminUserDeleteResponse(BaseModel):
    """Delete user response"""
    id: str
    deleted: bool
    message: str


# ============================================================================
# Project Management Schemas
# ============================================================================

class AdminProjectListItem(BaseModel):
    """Project list item for admin"""
    id: str
    name: str
    description: Optional[str]
    type: str
    status: str
    created_at: str  # ISO format string for frontend
    updated_at: str  # ISO format string for frontend
    owner_id: Optional[str] = Field(None, description="Project owner ID")
    owner_name: Optional[str] = Field(None, description="Project owner name")
    owner_email: Optional[str] = Field(None, description="Project owner email")
    # Count fields - support both naming conventions
    asset_count: int = Field(0, alias="assets_count")
    episode_count: int = Field(0, alias="episodes_count")
    storyboard_count: int = Field(0, alias="storyboards_count")

    model_config = ConfigDict(populate_by_name=True)


class AdminProjectListResponse(BaseModel):
    """Project list response for admin"""
    items: List[AdminProjectListItem]
    total: int
    page: int
    page_size: int
    total_pages: int


class AdminProjectFilter(BaseModel):
    """Project filter parameters"""
    status: Optional[str] = None
    type: Optional[str] = None
    user_id: Optional[str] = None
    search: Optional[str] = Field(None, description="Search by name")


class AdminProjectDetailResponse(BaseModel):
    """Project detail response for admin"""
    id: str
    name: str
    description: Optional[str]
    type: str
    status: str
    created_at: str  # ISO format string for frontend
    updated_at: str  # ISO format string for frontend
    owner_id: Optional[str]
    owner_name: Optional[str]
    owner_email: Optional[str]
    assets: List[Dict[str, Any]]
    episodes: List[Dict[str, Any]]
    storyboards: List[Dict[str, Any]]


class AdminProjectDeleteResponse(BaseModel):
    """Delete project response"""
    id: str
    deleted: bool
    message: str


# ============================================================================
# Task Monitoring Schemas
# ============================================================================

class AdminTaskListItem(BaseModel):
    """Task list item for admin"""
    id: str
    type: str
    status: str
    model: Optional[str]
    provider: Optional[str]
    created_at: str  # ISO format string for frontend
    updated_at: str  # ISO format string for frontend
    started_at: Optional[str]  # ISO format string for frontend
    completed_at: Optional[str]  # ISO format string for frontend
    duration: Optional[int] = Field(None, description="Task duration in seconds")
    user_id: Optional[str]
    user_name: Optional[str]
    user_email: Optional[str]
    project_id: Optional[str]
    project_name: Optional[str]
    retry_count: int
    max_retries: int
    error: Optional[str]


class TaskResultInfo(BaseModel):
    """Task result generation info"""
    # Common fields
    url: Optional[str] = None  # Generic result URL
    image_url: Optional[str] = Field(None, alias="imageUrl")
    video_url: Optional[str] = Field(None, alias="videoUrl")
    audio_url: Optional[str] = Field(None, alias="audioUrl")

    # Generation parameters used
    prompt: Optional[str] = None
    negative_prompt: Optional[str] = Field(None, alias="negativePrompt")
    model: Optional[str] = None
    provider: Optional[str] = None

    # Technical details
    duration_seconds: Optional[float] = Field(None, alias="durationSeconds")
    file_size: Optional[int] = Field(None, alias="fileSize")
    resolution: Optional[str] = None
    format: Optional[str] = None

    # Provider specific
    provider_task_id: Optional[str] = Field(None, alias="providerTaskId")
    cost: Optional[float] = None
    credits_used: Optional[float] = Field(None, alias="creditsUsed")

    # Metadata
    created_at: Optional[str] = Field(None, alias="createdAt")
    metadata: Optional[Dict[str, Any]] = None

    model_config = ConfigDict(populate_by_name=True)


class AdminTaskDetailResponse(BaseModel):
    """Task detail response with generation info"""
    # Basic task info
    id: str
    type: str
    status: str
    model: Optional[str]
    provider: Optional[str]
    created_at: str
    updated_at: str
    started_at: Optional[str]
    completed_at: Optional[str]
    duration: Optional[int]

    # User and project info
    user_id: Optional[str]
    user_name: Optional[str]
    user_email: Optional[str]
    project_id: Optional[str]
    project_name: Optional[str]

    # Retry and error info
    retry_count: int
    max_retries: int
    error: Optional[str]

    # Generation result info
    result: Optional[TaskResultInfo] = None

    # Request params (for debugging)
    params: Optional[Dict[str, Any]] = None


class AdminTaskListResponse(BaseModel):
    """Task list response for admin"""
    items: List[AdminTaskListItem]
    total: int
    page: int
    page_size: int
    total_pages: int


class AdminTaskFilter(BaseModel):
    """Task filter parameters"""
    status: Optional[str] = None
    type: Optional[str] = None
    provider: Optional[str] = None
    user_id: Optional[str] = None
    project_id: Optional[str] = None


class AdminTaskStatsResponse(BaseModel):
    """Task statistics response"""
    total: int
    by_status: Dict[str, int]
    by_type: Dict[str, int]
    by_provider: Dict[str, int]
    avg_processing_time: Optional[float] = Field(None, description="Average processing time in seconds")
    success_rate: float = Field(..., description="Success rate percentage")


class AdminTaskQueueStatusResponse(BaseModel):
    """Task queue status response"""
    queue_length: int
    processing_count: int
    max_workers: int
    active_workers: int
    pending_tasks: int
    retry_tasks: int


class AdminTaskRetryResponse(BaseModel):
    """Task retry response"""
    id: str
    status: str
    message: str
    retry_count: int


class AdminTaskDeleteResponse(BaseModel):
    """Delete task response"""
    id: str
    deleted: bool
    message: str


# ============================================================================
# System Settings Schemas
# ============================================================================

class SystemSettingItem(BaseModel):
    """System setting item"""
    key: str
    value: Any
    description: Optional[str]
    category: str
    is_editable: bool
    updated_at: Optional[str]


class SystemSettingsResponse(BaseModel):
    """System settings response"""
    settings: List[SystemSettingItem]
    categories: List[str]


class SystemSettingUpdateRequest(BaseModel):
    """Update system setting request"""
    value: Any


class SystemSettingUpdateResponse(BaseModel):
    """Update system setting response"""
    key: str
    value: Any
    updated_at: str
    message: str


class SystemConfigCategory(BaseModel):
    """System configuration category"""
    name: str
    description: str
    settings: List[SystemSettingItem]


class SystemMaintenanceModeRequest(BaseModel):
    """Toggle maintenance mode request"""
    enabled: bool
    message: Optional[str] = "System is under maintenance. Please try again later."


class SystemMaintenanceModeResponse(BaseModel):
    """Maintenance mode response"""
    enabled: bool
    message: str
    updated_at: str
