import os
import platform
import psutil
from datetime import datetime
from pathlib import Path

from fastapi import APIRouter

from mineru_flow.internal.config.config import media_dir, artifacts_dir, settings
from mineru_flow.internal.api.v1.schema.response.system import (
    HealthResponse,
)
from mineru_flow.version import version
from mineru_flow.internal.common.logging import get_api_logger

router = APIRouter(tags=["system"])
system_logger = get_api_logger().bind(endpoint="system")

# 配置
START_TIME = datetime.now().isoformat()


@router.get("/system/info")
async def get_system_status():
    """获取系统状态信息"""
    try:
        process = psutil.Process()
        memory_info = process.memory_info()
        system_logger.debug(
            "获取系统状态",
            pid=process.pid,
            uptime_seconds=(
                datetime.now() - datetime.fromtimestamp(process.create_time())
            ).total_seconds(),
        )

        return {
            "mediaDir": str(Path(media_dir)),
            "cacheDir": str(Path(artifacts_dir)),
            "databasePath": str(
                Path(settings.BASE_DATA_DIR).expanduser() / "mineru_flow.sqlite"
            ),
            "status": "ok",
            "version": version,
            "startTime": START_TIME,
            "environment": os.getenv("ENVIRONMENT", "production"),
            "pid": os.getpid(),
            "uptime": (
                datetime.now() - datetime.fromtimestamp(process.create_time())
            ).total_seconds(),
            "memory": {"rss": memory_info.rss, "vms": memory_info.vms},
            "platform": platform.system(),
            "pythonVersion": platform.python_version(),
        }
    except Exception as error:
        system_logger.error("系统信息获取失败", error=str(error))
        return {"status": "error", "error": str(error)}


@router.get("/system/health", response_model=HealthResponse)
async def health_check():
    """健康检查"""
    system_logger.debug("执行健康检查")
    return HealthResponse(
        status="healthy",
        timestamp=datetime.now().isoformat(),
        services={
            "api": True,
            "database": True,  # 简化检查，实际应该检查数据库连接
            "worker": True,  # 简化检查，实际应该检查 worker 状态
        },
    )
