# -*- coding: utf-8 -*-
import time
from threading import Thread

from fastapi import FastAPI,Request
from fastapi.responses import PlainTextResponse
from typing import Callable
from core.api_get_article import router as r1
from core.api_get_audio import router as r2
from core.api_get_article2 import router as r3
from core.api_get_word import router as r4
from core.api_get_spoken_language import router as r5
from core.api_get_article3 import router as r6
from core.api_article_annotation import router_article_annotation as r7

from tools.loglog import logger,log_err_e
from tools.del_expire_file import run_del_normal
from core.respone_format import *

app = FastAPI(title="AI相关功能接口", version="1.1")

app.include_router(r2, tags=["用户管理"])
app.include_router(r1, tags=["青提文章管理"])
app.include_router(r2, tags=["音频管理"])
app.include_router(r3, tags=["春笋文章管理"])
app.include_router(r4, tags=["生成word文档"])
app.include_router(r5, tags=["口语评测"])
app.include_router(r6, tags=["deepseek文章"])
app.include_router(r7, tags=["文章词义标注"])

@app.middleware("http")
async def add_process_time_header(request: Request, call_next: Callable):
    start_time = time.time()
    real_ip = request.headers.get("X-Real-IP")
    params = request.query_params
    path = request.url.path
    try:
        body = await request.json() if request.method in ["POST", "PUT", "PATCH"] else ""
    except:
        body =""
    logger.info(f"\n正式接口请求：{real_ip} {request.method} {path}\n查询参数：{params}\n携带参数：{body}")

    try:
        response = await call_next(request)
    except Exception as e:
        log_err_e(e,msg="http中间件错误捕捉")
        return resp_500(message=f"{type(e).__name__},{e}")

    process_time = str(round(time.time() - start_time, 2))
    response.headers["X-Process-Time"] = process_time

   
    if path not in ['/','/tts']:
        with open('log/time_log.txt', encoding='utf-8', mode='a')as f:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            f.write(f"{t}  路径:{path} - 用时:{process_time}\n")
    return response

@app.get("/")
@app.post("/")
def hello():
    return PlainTextResponse("hello world")

del_file_thread = Thread(target=run_del_normal, daemon=True)
del_file_thread.start()

