#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,re,json,sys
__path__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__path__)
sys.path.append(os.path.join(__path__, 'web_search_source'))
import uvicorn
import asyncio
import logging
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel

from save_es_database import ESsearch
from web_search_source.web_search_resource import webSearchResource



def setup_logger():
    # 创建logger对象
    logger = logging.getLogger('AI_planner')
    logger.setLevel(logging.INFO)

    # 确保日志目录存在
    __path__ = os.path.dirname(os.path.abspath(__file__))
    log_dir = os.path.join(__path__, "log")
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    log_file = os.path.join(log_dir, "AI_planner.log")

    # 创建文件处理器
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    # 创建控制台处理器
    # console_handler = logging.StreamHandler()
    # console_handler.setLevel(logging.INFO)

    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    # console_handler.setFormatter(formatter)

    # 添加处理器
    logger.addHandler(file_handler)
    # logger.addHandler(console_handler)

    return logger


# 创建全局logger实例
logger_es = setup_logger()


class Item(BaseModel):
    tableName: str = ""  # sop表名称
    bookCategory: str = "" # 图书类别：K12，童书，其他图书
    schoolStage: str = ""  # 学段 “初中”  “小学”  “高中”
    studentGrade: str = ""   # 年级
    subjectCategory: str = ""  # 学科 语文 数学
    bookVersion: str = ""  # 版本  如 人教版  通用版
    purpose: str = ""      # 目标读者的目的
    keyword: str = ""     # 需要查询的关键字



class ItemWebSearch(BaseModel):
    bookName: str = ""        # 书名
    bookClassify: str = ""    # 图书类别
    author: str = ""           # 图书作者
    introduction: str = ""     # 图书简介



app = FastAPI()

es_search = ESsearch(hosts=['http://localhost:9200'])
# 中文翻译为朝鲜文相关api接口

# 1、心跳检测
@app.get("/health/")
async def health():
    res = JSONResponse(status_code=200, content={"message": "no AI source up."})
    return res

# 2、es中 搜索 非AI资源
@app.post("/no_ai_source/")
async def no_ai_source(input: Item):
    # print("input: ",input)
    """
    接收一字典参数，返回es搜索的 非AI资源清单
    """

    try:
        input = json.loads(input.json())
        es_res = es_search.search(input)
        logger_es.info(f"ES search no_ai_source input : {input} ; \nes_search : {json.dumps(es_res, ensure_ascii=False, indent=4)}")
        res =  JSONResponse(status_code=200, content=es_res)

    except Exception as e:
        logger_es.error(f" no_ai_source input : {input}; error message : {e}")
        res = JSONResponse(
            status_code=500,
            content={"message": str(e)},
        )
    return res




if __name__ == "__main__":
    uvicorn.run(app="api_service:app", host="0.0.0.0", port=9860, workers=1) # 部署的服务是 9860



# 启动api服务  116.63.110.220 服务器
# netstat -ntlp | grep 9860
# cd /home/liuxin/work/AI_planner
# conda activate translate
# nohup python -u api_service.py > log/api_service.log 2>&1 &
# tail -f log/api_service.log
# tail -f log/AI_planner.log
# uvicorn api_service:app --host 0.0.0.0 --port 9860 --workers 1
