#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import uvicorn
import multiprocessing
import logging
import configparser
import gc
import psutil
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from conf.conf_fastapi import *

project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

app = FastAPI(
    title="Analysis API服务",
    description="从Tornado迁移到FastAPI的文本处理服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

app.add_middleware(
    GZipMiddleware,
    minimum_size=1000
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
    max_age=3600,
)

static_path = os.path.join(os.path.dirname(
    os.path.dirname(__file__)), "static")
if os.path.exists(static_path):
    app.mount("/static", StaticFiles(directory=static_path), name="static")


@app.middleware("http")
async def memory_cleanup_middleware(request: Request, call_next):
    try:
        response = await call_next(request)
    except Exception as e:
        logging.error(f"请求处理异常: {e}")
        response = JSONResponse({"code": "error", "msg": str(e)}, status_code=500)
    finally:
        gc.collect()
    return response


try:
    from controllers.AnalysisReportHandlers_fastapi import *
    app.include_router(router, tags=["批量报告"])
except ImportError as e:
    logging.error(f"导入路由失败: {e}")


@app.get("/")
async def root():
    """根路径"""
    return {"message": "Batch Report FastAPI服务正在运行", "version": "1.0.0"}


@app.get("/health")
async def health_check():
    process = psutil.Process()
    memory_info = process.memory_info()
    cpu_percent = process.cpu_percent(interval=0.1)
    return {
        "status": "healthy",
        "message": "服务运行正常",
        "memory_rss_mb": round(memory_info.rss / 1024 / 1024, 2),
        "memory_percent": round(process.memory_percent(), 2),
        "cpu_percent": round(cpu_percent, 2)
    }


@app.on_event("startup")
async def startup_event():
    gc.enable()
    gc.set_threshold(50000, 500, 10000)
    logging.info("FastAPI应用启动成功 - GC优化已启用")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logging.info("FastAPI应用正在关闭")

if __name__ == "__main__":
    server_config = config_fastapi().get_content("server")
    if server_config and "serverport" in server_config:
        port = int(server_config["serverport"])
    else:
        port = 8901
    
    cpu_count = multiprocessing.cpu_count()
    workers = cpu_count * 2 + 1
    
    uvicorn.run(
        "app_fastapi:app",
        host="0.0.0.0",
        port=port,
        workers=workers,
        reload=False,
        log_level="info",
        access_log=True,
        loop="uvloop",
        timeout_keep_alive=1800,
        timeout_graceful_shutdown=3600,
        http="httptools",
        limit_concurrency=500,
        limit_max_requests=5000,
        backlog=1024,
        proxy_headers=True,
        forwarded_allow_ips="*"
    )
