#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Modbus配置API模块
提供Modbus配置相关的API接口
"""

from typing import Dict, List, Any, Optional
from fastapi import APIRouter, Query, Path, Request, Body

from routes.common_api import format_response, error_response
from utils.logger import get_logger
from services.modbus_config_service import ModbusConfigService
from routes.model.modbus_config_model import (
    ModbusConfigAddRequest,
    ModbusConfigUpdateRequest,
    ModbusConnectionTestRequest,
    ModbusConfigListParams
)

# 创建路由
router = APIRouter(
    prefix="/api/vwed-modbus-config",
    tags=["VWED Modbus配置"]
)

# 设置日志
logger = get_logger("app.modbus_config_api")

@router.post("/add")
async def add_modbus_config(
    request: Request,
    config_data: ModbusConfigAddRequest = Body(..., description="Modbus配置信息")
):
    """
    新增Modbus配置
    
    Args:
        config_data: Modbus配置信息，包含name、ip、port等字段
        
    Returns:
        包含新增结果的响应
    """
    try:
        # 转换为字典
        config_dict = config_data.model_dump(exclude_unset=True)
        result = await ModbusConfigService.add_modbus_config(config_dict)
        if not result["success"]:
            return error_response(message=result["message"], code=400)
        return format_response(data=result["data"], message=result["message"])
    except Exception as e:
        logger.error(f"新增Modbus配置失败: {str(e)}")
        return error_response(message=f"新增Modbus配置失败: {str(e)}", code=500)

@router.delete("/{config_id}")
async def delete_modbus_config(
    config_id: str = Path(..., description="配置ID")
):
    """
    删除Modbus配置
    
    Args:
        config_id: Modbus配置ID
        
    Returns:
        包含删除结果的响应
    """
    try:
        result = await ModbusConfigService.delete_modbus_config(config_id)
        if not result["success"]:
            return error_response(message=result["message"], code=404)
        return format_response(message=result["message"])
    except Exception as e:
        logger.error(f"删除Modbus配置失败: {str(e)}")
        return error_response(message=f"删除Modbus配置失败: {str(e)}", code=500)

@router.post("/test-connection")
async def test_modbus_connection(
    connection_data: ModbusConnectionTestRequest = Body(..., description="Modbus连接参数")
):
    """
    测试Modbus连接
    
    Args:
        connection_data: Modbus连接参数，包含ip、port、slave_id等
        
    Returns:
        包含连接测试结果的响应
    """
    try:
        # 转换为字典
        connection_dict = connection_data.model_dump(exclude_unset=True)
        result = await ModbusConfigService.test_modbus_connection(connection_dict)
        if not result["success"]:
            return error_response(message=result["message"], code=400)
        return format_response(data=result["data"], message=result["message"])
    except Exception as e:
        logger.error(f"测试Modbus连接失败: {str(e)}")
        return error_response(message=f"测试Modbus连接失败: {str(e)}", code=500)

@router.get("/list")
async def get_modbus_config_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, description="每页数量"),
    name: Optional[str] = Query(None, description="配置名称"),
    ip: Optional[str] = Query(None, description="设备IP地址")
):
    """
    获取Modbus配置列表
    
    Args:
        page: 页码
        size: 每页数量
        name: 配置名称，用于筛选
        ip: 设备IP地址，用于筛选
        
    Returns:
        包含Modbus配置列表的响应
    """
    try:
        # 创建查询参数对象
        params = ModbusConfigListParams(
            pageNum=page,
            pageSize=size,
            name=name,
            ip=ip
        )
        result = await ModbusConfigService.get_modbus_config_list(
            page=params.pageNum,
            size=params.pageSize,
            name=params.name,
            ip=params.ip
        )
        if not result["success"]:
            return error_response(message=result["message"], code=500)
        return format_response(data=result["data"], message=result["message"])
    except Exception as e:
        logger.error(f"获取Modbus配置列表失败: {str(e)}")
        return error_response(message=f"获取Modbus配置列表失败: {str(e)}", code=500) 
    
    
@router.put("/{config_id}")
async def update_modbus_config(
    config_id: str = Path(..., description="配置ID"),
    config_data: ModbusConfigUpdateRequest = Body(..., description="Modbus配置信息")
):
    """
    修改Modbus配置
    
    Args:
        config_id: Modbus配置ID
        config_data: 修改后的Modbus配置信息
        
    Returns:
        包含修改结果的响应
    """
    try:
        # 转换为字典
        config_dict = config_data.model_dump(exclude_unset=True)
        result = await ModbusConfigService.update_modbus_config(config_id, config_dict)
        if not result["success"]:
            return error_response(message=result["message"], code=400)
        return format_response(data=result["data"], message=result["message"])
    except Exception as e:
        logger.error(f"修改Modbus配置失败: {str(e)}")
        return error_response(message=f"修改Modbus配置失败: {str(e)}", code=500)

@router.get("/{config_id}")
async def get_modbus_config_detail(
    config_id: str = Path(..., description="配置ID")
):
    """
    获取指定Modbus配置详情
    
    Args:
        config_id: Modbus配置ID
        
    Returns:
        包含Modbus配置详情的响应
    """
    try:
        result = await ModbusConfigService.get_modbus_config_detail(config_id)
        if not result["success"]:
            return error_response(message=result["message"], code=404)
        return format_response(data=result["data"], message=result["message"])
    except Exception as e:
        logger.error(f"获取Modbus配置详情失败: {str(e)}")
        return error_response(message=f"获取Modbus配置详情失败: {str(e)}", code=500)
