"""
Admin Service - Dashboard Module

包含仪表板统计和系统资源相关功能。
"""

import logging
import time
from typing import Optional

from sqlmodel import Session, select, func
from datetime import datetime

from src.config.database import engine
from src.models.entities import UserDB, ProjectDB, TaskDB
from src.models.admin_schemas import (
    DashboardStatsResponse,
    DashboardActivityResponse,
    ActivityItem,
    SystemResourceInfo,
)

logger = logging.getLogger(__name__)


def _timestamp_to_iso(ts: Optional[float]) -> str:
    """Convert timestamp to ISO format string"""
    if not ts:
        return ""
    return datetime.fromtimestamp(ts).isoformat()


class DashboardService:
    """Dashboard service for admin operations"""

    async def get_dashboard_stats(self) -> DashboardStatsResponse:
        """Get dashboard statistics"""
        with Session(engine) as session:
            # User counts
            total_users = session.exec(select(func.count()).select_from(UserDB)).one()

            # Project counts
            total_projects = session.exec(
                select(func.count()).select_from(ProjectDB)
            ).one()

            # Task counts by status
            total_tasks = session.exec(select(func.count()).select_from(TaskDB)).one()

            active_tasks = session.exec(
                select(func.count()).select_from(TaskDB).where(TaskDB.status == "processing")
            ).one()

            pending_tasks = session.exec(
                select(func.count()).select_from(TaskDB).where(TaskDB.status == "pending")
            ).one()

            failed_tasks = session.exec(
                select(func.count()).select_from(TaskDB).where(TaskDB.status == "failed")
            ).one()

            completed_tasks = session.exec(
                select(func.count()).select_from(TaskDB).where(TaskDB.status == "success")
            ).one()

            return DashboardStatsResponse(
                total_users=total_users,
                total_projects=total_projects,
                total_tasks=total_tasks,
                active_tasks=active_tasks,
                pending_tasks=pending_tasks,
                failed_tasks=failed_tasks,
                completed_tasks=completed_tasks,
            )

    async def get_system_resources(self) -> SystemResourceInfo:
        """Get system resource information"""
        try:
            import psutil

            cpu_usage = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            boot_time = psutil.boot_time()
            uptime = time.time() - boot_time

            return SystemResourceInfo(
                cpu_usage=cpu_usage,
                memory_usage=memory.percent,
                disk_usage=disk.percent,
                uptime=uptime,
            )
        except ImportError:
            # psutil not available, return mock data
            return SystemResourceInfo(
                cpu_usage=0.0,
                memory_usage=0.0,
                disk_usage=0.0,
                uptime=0.0,
            )

    async def get_recent_activity(
        self, limit: int = 20
    ) -> DashboardActivityResponse:
        """Get recent system activity"""
        # For now, we'll combine recent users, projects, and tasks
        # In a production system, you might have a dedicated activity log table
        activities = []

        with Session(engine) as session:
            # Recent users
            recent_users = session.exec(
                select(UserDB).order_by(UserDB.created_at.desc()).limit(limit // 3)
            ).all()

            for user in recent_users:
                activities.append(
                    ActivityItem(
                        id=f"user_{user.id}",
                        type="user",
                        action="created",
                        user_id=user.id,
                        user_name=user.username,
                        target_id=user.id,
                        target_type="user",
                        details={"email": user.email},
                        created_at=datetime.fromtimestamp(user.created_at).isoformat(),
                    )
                )

            # Recent projects
            recent_projects = session.exec(
                select(ProjectDB).order_by(ProjectDB.created_at.desc()).limit(limit // 3)
            ).all()

            for project in recent_projects:
                activities.append(
                    ActivityItem(
                        id=f"project_{project.id}",
                        type="project",
                        action="created",
                        user_id=None,
                        user_name=None,
                        target_id=project.id,
                        target_type="project",
                        details={"name": project.name, "type": project.type},
                        created_at=datetime.fromtimestamp(project.created_at).isoformat(),
                    )
                )

            # Recent tasks
            recent_tasks = session.exec(
                select(TaskDB).order_by(TaskDB.created_at.desc()).limit(limit // 3)
            ).all()

            for task in recent_tasks:
                activities.append(
                    ActivityItem(
                        id=f"task_{task.id}",
                        type="task",
                        action=f"status_changed",
                        user_id=task.user_id,
                        user_name=None,
                        target_id=task.id,
                        target_type="task",
                        details={
                            "status": task.status,
                            "type": task.type,
                            "model": task.model,
                        },
                        created_at=datetime.fromtimestamp(task.created_at).isoformat(),
                    )
                )

        # Sort by created_at descending
        activities.sort(key=lambda x: x.created_at, reverse=True)
        activities = activities[:limit]

        return DashboardActivityResponse(
            items=activities,
            total=len(activities),
        )
