"""
MCPStore API - Store级别路由
包含所有Store级别的API端点
"""

from typing import Optional, Dict, Any

from fastapi import APIRouter, HTTPException, Depends, Request
from mcpstore import MCPStore
from mcpstore.core.models.common import APIResponse
from mcpstore.core.models.service import JsonUpdateRequest

from .api_decorators import handle_exceptions, get_store
from .api_models import (
    ToolExecutionRecordResponse, ToolRecordsResponse, ToolRecordsSummaryResponse,
    NetworkEndpointResponse, SystemResourceInfoResponse, NetworkEndpointCheckRequest,
    SimpleToolExecutionRequest
)

# 创建Store级别的路由器
store_router = APIRouter()

# === Store 级别操作 ===
@store_router.post("/for_store/add_service", response_model=APIResponse)
@handle_exceptions
async def store_add_service(
    payload: Optional[Dict[str, Any]] = None
):
    """Store 级别注册服务
    支持三种模式：
    1. 空参数注册：注册所有 mcp.json 中的服务
       POST /for_store/add_service
    
    2. URL方式添加服务：
       POST /for_store/add_service
       {
           "name": "weather",
           "url": "https://weather-api.example.com/mcp",
           "transport": "streamable-http"
       }
    
    3. 命令方式添加服务（本地服务）：
       POST /for_store/add_service
       {
           "name": "assistant",
           "command": "python",
           "args": ["./assistant_server.py"],
           "env": {"DEBUG": "true"},
           "working_dir": "/path/to/service"
       }

       注意：本地服务需要确保：
       - 命令路径正确且可执行
       - 工作目录存在且有权限
       - 环境变量设置正确
    """
    try:
        store = get_store()
        
        if payload is None:
            # 空参数：注册所有服务
            result = await store.for_store().add_service_async()
        else:
            # 有参数：添加特定服务
            result = await store.for_store().add_service_async(payload)
        
        return APIResponse(
            success=bool(result),
            data=result,
            message="Service registration completed successfully" if result else "Service registration failed"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=None,
            message=f"Failed to register service: {str(e)}"
        )

@store_router.get("/for_store/list_services", response_model=APIResponse)
@handle_exceptions
async def store_list_services():
    """Store 级别获取服务列表"""
    try:
        store = get_store()
        context = store.for_store()
        services = context.list_services()
        
        # 转换为字典格式
        services_data = [
            {
                "name": service.name,
                "status": service.status,
                "transport": getattr(service, 'transport', 'unknown'),
                "config": getattr(service, 'config', {}),
                "client_id": getattr(service, 'client_id', None)
            }
            for service in services
        ]
        
        return APIResponse(
            success=True,
            data=services_data,
            message=f"Retrieved {len(services_data)} services"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=[],
            message=f"Failed to retrieve services: {str(e)}"
        )

@store_router.get("/for_store/list_tools", response_model=APIResponse)
@handle_exceptions
async def store_list_tools():
    """Store 级别获取工具列表"""
    try:
        store = get_store()
        context = store.for_store()
        # 使用SDK的统计方法
        result = context.get_tools_with_stats()

        return APIResponse(
            success=True,
            data=result["tools"],
            metadata=result["metadata"],
            message=f"Retrieved {result['metadata']['total_tools']} tools from {result['metadata']['services_count']} services"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=[],
            message=f"Failed to retrieve tools: {str(e)}"
        )

@store_router.get("/for_store/check_services", response_model=APIResponse)
@handle_exceptions
async def store_check_services():
    """Store 级别健康检查"""
    try:
        store = get_store()
        context = store.for_store()
        health_status = context.check_services()

        return APIResponse(
            success=True,
            data=health_status,
            message="Health check completed successfully"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={"error": str(e)},
            message=f"Health check failed: {str(e)}"
        )

@store_router.post("/for_store/use_tool", response_model=APIResponse)
@handle_exceptions
async def store_use_tool(request: SimpleToolExecutionRequest):
    """Store 级别工具执行"""
    try:
        import time
        import uuid

        # 记录执行开始时间
        start_time = time.time()
        trace_id = str(uuid.uuid4())[:8]

        # 🔧 直接使用SDK的use_tool_async方法，它已经包含了完整的工具解析逻辑
        # SDK会自动处理：工具名称解析、服务推断、格式转换等
        store = get_store()
        result = await store.for_store().use_tool_async(request.tool_name, request.args)

        # 计算执行时间
        duration_ms = int((time.time() - start_time) * 1000)

        return APIResponse(
            success=True,
            data=result,
            metadata={
                "execution_time_ms": duration_ms,
                "trace_id": trace_id,
                "tool_name": request.tool_name,
                "service_name": request.service_name
            },
            message=f"Tool '{request.tool_name}' executed successfully in {duration_ms}ms"
        )
    except Exception as e:
        duration_ms = int((time.time() - start_time) * 1000) if 'start_time' in locals() else 0
        return APIResponse(
            success=False,
            data={"error": str(e)},
            metadata={
                "execution_time_ms": duration_ms,
                "trace_id": trace_id if 'trace_id' in locals() else "unknown",
                "tool_name": request.tool_name,
                "service_name": request.service_name
            },
            message=f"Tool execution failed: {str(e)}"
        )

@store_router.post("/for_store/get_service_info", response_model=APIResponse)
@handle_exceptions
async def store_get_service_info(request: Request):
    """Store 级别获取服务信息"""
    try:
        body = await request.json()
        service_name = body.get("name")
        
        if not service_name:
            raise HTTPException(status_code=400, detail="Service name is required")
        
        store = get_store()
        context = store.for_store()
        service_info = context.get_service_info(service_name)
        
        return APIResponse(
            success=True,
            data=service_info,
            message=f"Service info retrieved for '{service_name}'"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to get service info: {str(e)}"
        )

@store_router.put("/for_store/update_service/{service_name}", response_model=APIResponse)
@handle_exceptions
async def store_update_service(service_name: str, request: Request):
    """Store 级别更新服务配置"""
    try:
        body = await request.json()
        
        store = get_store()
        context = store.for_store()
        result = await context.update_service_async(service_name, body)
        
        return APIResponse(
            success=bool(result),
            data=result,
            message=f"Service '{service_name}' updated successfully" if result else f"Failed to update service '{service_name}'"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to update service '{service_name}': {str(e)}"
        )

@store_router.delete("/for_store/delete_service/{service_name}", response_model=APIResponse)
@handle_exceptions
async def store_delete_service(service_name: str):
    """Store 级别删除服务"""
    try:
        store = get_store()
        context = store.for_store()
        result = await context.delete_service_async(service_name)
        
        return APIResponse(
            success=bool(result),
            data=result,
            message=f"Service '{service_name}' deleted successfully" if result else f"Failed to delete service '{service_name}'"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to delete service '{service_name}': {str(e)}"
        )

@store_router.get("/for_store/show_mcpconfig", response_model=APIResponse)
@handle_exceptions
async def store_show_mcpconfig():
    """Store 级别获取MCP配置"""
    try:
        store = get_store()
        context = store.for_store()
        config = context.show_mcpconfig()

        return APIResponse(
            success=True,
            data=config,
            message="MCP configuration retrieved successfully"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to get MCP configuration: {str(e)}"
        )

@store_router.post("/for_store/update_config", response_model=APIResponse)
@handle_exceptions
async def store_update_config(request: JsonUpdateRequest):
    """Store 级别更新配置"""
    try:
        store = get_store()
        context = store.for_store()
        result = await context.update_config_async(request.config)

        return APIResponse(
            success=bool(result),
            data=result,
            message="Configuration updated successfully" if result else "Failed to update configuration"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to update configuration: {str(e)}"
        )

@store_router.post("/for_store/update_config_two_step", response_model=APIResponse)
@handle_exceptions
async def store_update_config_two_step(request: Request):
    """Store 级别两步操作：更新MCP JSON文件 + 重新注册服务"""
    try:
        body = await request.json()
        config = body.get("config")

        if not config:
            raise HTTPException(status_code=400, detail="Config is required")

        store = get_store()
        result = await store.for_store().update_config_two_step(config)

        return APIResponse(
            success=result["overall_success"],
            data=result,
            message="Configuration updated successfully" if result["overall_success"]
                   else f"Partial success: JSON updated={result['step1_json_update']}, Services registered={result['step2_service_registration']}"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={"error": str(e)},
            message=f"Failed to update configuration: {str(e)}"
        )

@store_router.post("/for_store/delete_service_two_step", response_model=APIResponse)
@handle_exceptions
async def store_delete_service_two_step(request: Request):
    """Store 级别两步操作：从MCP JSON文件删除服务 + 注销服务"""
    try:
        body = await request.json()
        service_name = body.get("service_name") or body.get("name")

        if not service_name:
            raise HTTPException(status_code=400, detail="Service name is required")

        store = get_store()
        result = await store.for_store().delete_service_two_step(service_name)

        return APIResponse(
            success=result["overall_success"],
            data=result,
            message=f"Service {service_name} deleted successfully" if result["overall_success"]
                   else f"Partial success: JSON deleted={result['step1_json_delete']}, Service unregistered={result['step2_service_unregistration']}"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={"error": str(e)},
            message=f"Failed to delete service: {str(e)}"
        )

@store_router.post("/for_store/reset_config", response_model=APIResponse)
@handle_exceptions
async def store_reset_config():
    """Store 级别重置配置"""
    try:
        store = get_store()
        success = await store.for_store().reset_config_async()
        return APIResponse(
            success=success,
            data=success,
            message="Store configuration reset successfully" if success else "Failed to reset store configuration"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=False,
            message=f"Failed to reset store configuration: {str(e)}"
        )

@store_router.post("/for_store/reset_mcp_json_file", response_model=APIResponse)
@handle_exceptions
async def store_reset_mcp_json_file():
    """Store 级别直接重置MCP JSON配置文件"""
    try:
        store = get_store()
        success = await store.for_store().reset_mcp_json_file_async()
        return APIResponse(
            success=success,
            data=success,
            message="MCP JSON file reset successfully" if success else "Failed to reset MCP JSON file"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=False,
            message=f"Failed to reset MCP JSON file: {str(e)}"
        )

# === Store 级别统计和监控 ===
@store_router.get("/for_store/get_stats", response_model=APIResponse)
@handle_exceptions
async def store_get_stats():
    """Store 级别获取系统统计信息"""
    try:
        store = get_store()
        context = store.for_store()
        # 使用SDK的统计方法
        stats = context.get_system_stats()

        return APIResponse(
            success=True,
            data=stats,
            message="System statistics retrieved successfully"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to get system statistics: {str(e)}"
        )

@store_router.get("/for_store/health", response_model=APIResponse)
@handle_exceptions
async def store_health_check():
    """Store 级别系统健康检查"""
    try:
        # 检查Store级别健康状态
        store = get_store()
        store_health = await store.for_store().check_services_async()

        # 基本系统信息
        health_info = {
            "status": "healthy",
            "timestamp": store_health.get("timestamp") if isinstance(store_health, dict) else None,
            "store": store_health,
            "system": {
                "api_version": "0.2.0",
                "store_initialized": bool(store),
                "orchestrator_status": store_health.get("orchestrator_status", "unknown") if isinstance(store_health, dict) else "unknown",
                "context": "store"
            }
        }

        return APIResponse(
            success=True,
            data=health_info,
            message="Health check completed successfully"
        )

    except Exception as e:
        return APIResponse(
            success=False,
            data={
                "status": "unhealthy",
                "error": str(e),
                "context": "store"
            },
            message=f"Health check failed: {str(e)}"
        )

@store_router.get("/for_store/tool_records", response_model=APIResponse)
async def get_store_tool_records(limit: int = 50, store: MCPStore = Depends(get_store)):
    """获取Store级别的工具执行记录"""
    try:
        store = get_store()
        records_data = await store.for_store().get_tool_records_async(limit)

        # 转换执行记录
        executions = [
            ToolExecutionRecordResponse(
                id=record["id"],
                tool_name=record["tool_name"],
                service_name=record["service_name"],
                params=record["params"],
                result=record["result"],
                error=record["error"],
                response_time=record["response_time"],
                execution_time=record["execution_time"],
                timestamp=record["timestamp"]
            ).model_dump() for record in records_data["executions"]
        ]

        # 转换汇总信息
        summary = ToolRecordsSummaryResponse(
            total_executions=records_data["summary"]["total_executions"],
            by_tool=records_data["summary"]["by_tool"],
            by_service=records_data["summary"]["by_service"]
        ).model_dump()

        response_data = ToolRecordsResponse(
            executions=executions,
            summary=summary
        ).model_dump()

        return APIResponse(
            success=True,
            data=response_data,
            message=f"Retrieved {len(executions)} tool execution records"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={
                "executions": [],
                "summary": {
                    "total_executions": 0,
                    "by_tool": {},
                    "by_service": {}
                }
            },
            message=f"Failed to get tool records: {str(e)}"
        )

@store_router.post("/for_store/network_check", response_model=APIResponse)
async def check_store_network_endpoints(request: NetworkEndpointCheckRequest, store: MCPStore = Depends(get_store)):
    """检查Store级别的网络端点状态"""
    try:
        store = get_store()
        endpoints = await store.for_store().check_network_endpoints(request.endpoints)

        endpoints_data = [
            NetworkEndpointResponse(
                endpoint_name=endpoint.endpoint_name,
                url=endpoint.url,
                status=endpoint.status,
                response_time=endpoint.response_time,
                last_checked=endpoint.last_checked,
                uptime_percentage=endpoint.uptime_percentage
            ).dict() for endpoint in endpoints
        ]

        return APIResponse(
            success=True,
            data=endpoints_data,
            message="Network endpoints checked successfully"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data=[],
            message=f"Failed to check network endpoints: {str(e)}"
        )

@store_router.get("/for_store/system_resources", response_model=APIResponse)
async def get_store_system_resources(store: MCPStore = Depends(get_store)):
    """获取Store级别的系统资源信息"""
    try:
        store = get_store()
        resources = await store.for_store().get_system_resource_info_async()

        return APIResponse(
            success=True,
            data=SystemResourceInfoResponse(
                server_uptime=resources.server_uptime,
                memory_total=resources.memory_total,
                memory_used=resources.memory_used,
                memory_percentage=resources.memory_percentage,
                disk_usage_percentage=resources.disk_usage_percentage,
                network_traffic_in=resources.network_traffic_in,
                network_traffic_out=resources.network_traffic_out
            ).dict(),
            message="System resources retrieved successfully"
        )
    except Exception as e:
        return APIResponse(
            success=False,
            data={},
            message=f"Failed to get system resources: {str(e)}"
        )
