"""
MCPStore API 应用工厂
支持使用指定的MCPStore实例创建API应用
"""

import logging
import time
from contextlib import asynccontextmanager
from fastapi import Request, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

from mcpstore.core.store import MCPStore

# 全局store实例（由MCPStore.start_api_server设置）
_global_store_instance: MCPStore = None

logger = logging.getLogger(__name__)

def get_store() -> MCPStore:
    """获取当前的MCPStore实例"""
    global _global_store_instance
    
    if _global_store_instance is None:
        # 如果没有设置全局实例，使用默认配置创建
        logger.warning("No global store instance found, creating default store")
        _global_store_instance = MCPStore.setup_store()
    
    return _global_store_instance

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    store = get_store()
    
    logger.info("Initializing MCPStore API service...")
    
    if store.is_using_data_space():
        workspace_dir = store.get_workspace_dir()
        logger.info(f"Using data space: {workspace_dir}")
    else:
        logger.info("Using default configuration")
    
    # 设置编排器
    try:
        await store.orchestrator.setup()
        logger.info("MCPStore API service initialized successfully")
    except Exception as e:
        logger.error(f"Failed to setup orchestrator: {e}")
        raise
    
    yield  # 应用运行期间
    
    # 应用关闭时的清理
    logger.info("Shutting down MCPStore API service...")
    
    try:
        # 清理编排器资源
        await store.orchestrator.cleanup()
        logger.info("MCPStore API service shutdown completed")
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")

def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    
    Returns:
        FastAPI: 配置好的应用实例
    """
    store = get_store()
    
    # 创建应用实例
    app = FastAPI(
        title="MCPStore API",
        description="MCPStore HTTP API Service",
        version="0.2.0",
        lifespan=lifespan
    )
    
    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 导入并注册路由
    from .api import router
    app.include_router(router)
    
    # 注册异常处理
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        errors = exc.errors()
        error_messages = []
        for error in errors:
            loc = " -> ".join([str(l) for l in error["loc"] if l != "body"])
            msg = error["msg"]
            error_messages.append(f"{loc}: {msg}")

        return JSONResponse(
            status_code=400,
            content={
                "success": False,
                "message": "Validation error",
                "data": error_messages
            }
        )

    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        logger.error(f"Unhandled exception in {request.method} {request.url.path}: {exc}")
        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "message": "Internal server error",
                "data": str(exc)
            }
        )

    # 添加请求日志和性能监控中间件
    @app.middleware("http")
    async def log_requests_and_monitor(request: Request, call_next):
        """记录请求日志并监控性能"""
        start_time = time.time()
        
        # 增加活跃连接数
        try:
            store.for_store().increment_active_connections()
        except:
            pass  # 忽略监控错误
        
        try:
            response = await call_next(request)
            process_time = (time.time() - start_time) * 1000
            
            # 记录API调用
            try:
                store.for_store().record_api_call(process_time)
            except:
                pass  # 忽略监控错误

            # 只记录错误和较慢的请求
            if response.status_code >= 400 or process_time > 1000:
                logger.info(
                    f"{request.method} {request.url.path} - "
                    f"Status: {response.status_code}, Duration: {process_time:.2f}ms"
                )
            return response
        except Exception as e:
            process_time = (time.time() - start_time) * 1000
            logger.error(
                f"{request.method} {request.url.path} - "
                f"Error: {e}, Duration: {process_time:.2f}ms"
            )
            raise
        finally:
            # 减少活跃连接数
            try:
                store.for_store().decrement_active_connections()
            except:
                pass  # 忽略监控错误
    
    # 添加健康检查端点
    @app.get("/health")
    async def health_check():
        """健康检查端点"""
        try:
            store = get_store()
            workspace_info = None
            
            if store.is_using_data_space():
                workspace_info = {
                    "workspace_dir": store.get_workspace_dir(),
                    "mcp_config_path": store.config.json_path
                }
            
            return {
                "status": "healthy",
                "service": "MCPStore API",
                "version": "0.2.0",
                "timestamp": time.time(),
                "data_space": workspace_info
            }
        except Exception as e:
            logger.error(f"Health check failed: {e}")
            return JSONResponse(
                status_code=503,
                content={
                    "status": "unhealthy",
                    "service": "MCPStore API",
                    "error": str(e),
                    "timestamp": time.time()
                }
            )
    
    # 添加数据空间信息端点
    @app.get("/workspace/info")
    async def workspace_info():
        """获取工作空间信息"""
        try:
            store = get_store()
            
            if store.is_using_data_space():
                space_info = store.get_data_space_info()
                return {
                    "success": True,
                    "data": space_info,
                    "message": "Workspace information retrieved successfully"
                }
            else:
                return {
                    "success": True,
                    "data": {
                        "using_data_space": False,
                        "mcp_config_path": store.config.json_path,
                        "message": "Using default configuration"
                    },
                    "message": "Default workspace information"
                }
        except Exception as e:
            logger.error(f"Failed to get workspace info: {e}")
            return JSONResponse(
                status_code=500,
                content={
                    "success": False,
                    "message": f"Failed to get workspace info: {str(e)}",
                    "data": {}
                }
            )
    
    return app

# 为了向后兼容，保留原有的app实例
app = create_app()
