"""
Gift-Advisor SaaS 主应用
SaaS云服务入口，支持订阅管理、电商集成、佣金系统
"""
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import time
import logging
from datetime import datetime

# 导入配置
from app.config import settings

# 导入路由
from app.api.endpoints import subscription, recommendation, commission, analytics

# 设置日志
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title="Gift-Advisor SaaS API",
    description="AI礼物推荐专家云服务，支持订阅管理、电商集成、佣金系统",
    version="2.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 自定义中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """记录API请求日志"""
    start_time = time.time()
    
    # 获取请求信息
    client_host = request.client.host if request.client else "unknown"
    path = request.url.path
    method = request.method
    
    # 记录请求开始
    logger.info(f"Request started: {method} {path} from {client_host}")
    
    try:
        response = await call_next(request)
    except Exception as e:
        # 记录异常
        logger.error(f"Request failed: {method} {path} - {str(e)}")
        raise e
    
    # 计算处理时间
    process_time = time.time() - start_time
    
    # 记录请求完成
    status_code = response.status_code
    logger.info(
        f"Request completed: {method} {path} - "
        f"Status: {status_code} - "
        f"Duration: {process_time:.3f}s"
    )
    
    # 添加处理时间到响应头
    response.headers["X-Process-Time"] = str(process_time)
    
    return response

# 全局异常处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """处理HTTP异常"""
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "message": exc.detail,
            "timestamp": datetime.now().isoformat()
        }
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """处理未捕获的异常"""
    logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
    
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "message": "Internal server error",
            "timestamp": datetime.now().isoformat()
        }
    )

# 包含路由
app.include_router(
    subscription.router,
    prefix="/api/v1/subscription",
    tags=["subscription"]
)

app.include_router(
    recommendation.router,
    prefix="/api/v1/recommendation",
    tags=["recommendation"]
)

app.include_router(
    commission.router,
    prefix="/api/v1/commission",
    tags=["commission"]
)

app.include_router(
    analytics.router,
    prefix="/api/v1/analytics",
    tags=["analytics"]
)

# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "service": "gift-advisor-saas",
        "version": "2.0.0"
    }

@app.get("/")
async def root():
    """根目录"""
    return {
        "message": "Welcome to Gift-Advisor SaaS API",
        "version": "2.0.0",
        "docs": "/docs",
        "subscription": "/api/v1/subscription",
        "recommendation": "/api/v1/recommendation",
        "commission": "/api/v1/commission"
    }