#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：system.py
模块描述：系统管理 API 路由（系统信息、运行环境）

作者：czj
创建日期：2026-07-29
最后修改：2026-07-29
"""

import logging
import platform
import sys
import time
from pathlib import Path

from fastapi import APIRouter, Depends
from sqlalchemy import func, select, text
from sqlalchemy.ext.asyncio import AsyncSession

from app.config import settings
from app.database import get_db
from app.models.module import Module
from app.models.test_case import TestCase

logger = logging.getLogger(__name__)

router = APIRouter()

# 应用启动时间（模块加载时记录）
_START_TIME = time.time()


@router.get("/info", response_model=dict)
async def get_system_info(db: AsyncSession = Depends(get_db)):
    """
    获取系统运行信息

    返回应用版本、运行环境、数据库状态、用例/模块统计等。

    Returns:
        dict: 系统信息
    """
    # 数据库类型
    is_sqlite = "sqlite" in settings.DATABASE_URL
    db_type = "sqlite" if is_sqlite else "mysql"

    # 数据库大小
    db_size_mb = 0.0
    try:
        if is_sqlite:
            # SQLite：直接读取文件大小
            db_path = settings.DATABASE_URL.replace("sqlite+aiosqlite:///", "")
            # 处理相对路径
            p = Path(db_path)
            if not p.is_absolute():
                # 相对路径通常相对 backend/ 目录
                p = Path.cwd() / p
            if p.exists():
                db_size_mb = round(p.stat().st_size / (1024 * 1024), 2)
        else:
            # MySQL：查询 information_schema
            result = await db.execute(
                text(
                    "SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) "
                    "AS size_mb FROM information_schema.tables "
                    "WHERE table_schema = DATABASE()"
                )
            )
            row = result.scalar()
            db_size_mb = float(row) if row else 0.0
    except Exception as e:
        logger.warning(f"获取数据库大小失败: {e}")
        db_size_mb = 0.0

    # 模块 / 用例总数
    total_modules = 0
    total_cases = 0
    try:
        result = await db.execute(select(func.count(Module.id)))
        total_modules = result.scalar() or 0
        result = await db.execute(select(func.count(TestCase.id)))
        total_cases = result.scalar() or 0
    except Exception as e:
        logger.warning(f"获取模块/用例统计失败: {e}")

    # 运行时间
    uptime_seconds = int(time.time() - _START_TIME)
    hours, remainder = divmod(uptime_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    uptime_text = f"{hours}小时{minutes}分钟{seconds}秒" if hours else f"{minutes}分钟{seconds}秒"

    return {
        "app_name": settings.APP_NAME,
        "backend_version": settings.APP_VERSION,
        "python_version": platform.python_version(),
        "platform": platform.platform(),
        "os": f"{platform.system()} {platform.release()}",
        "uptime_seconds": uptime_seconds,
        "uptime_text": uptime_text,
        "db_type": db_type,
        "db_size_mb": db_size_mb,
        "total_modules": total_modules,
        "total_cases": total_cases,
        "debug": settings.DEBUG,
        "playwright_headless": settings.PLAYWRIGHT_HEADLESS,
        "frontend_version": "1.0.0",
    }
