# -*- coding: utf-8 -*-
from fastapi import FastAPI, Form, HTTPException, Request,status,APIRouter,Query,Path
from tools.loglog import logger
from gpt.get_article import GetArticle
from gpt.query_oss_file import query_file_content
from core.respone_format import *

from pydantic import BaseModel, ValidationError, conint
from typing import List, Optional


router = APIRouter()
get_article = GetArticle()


class ArticleRequest(BaseModel):
    meaning_ids: List[conint(ge=1)] 
    callback_url: Optional[str] = None 
    demo_name: Optional[str] = "无" 
    student_stage: Optional[int] = 1 
    vocabulary: Optional[int] = 500 
    class_id :Optional[int]

@router.post("/article")
def post_article(json_data:ArticleRequest,request:Request):
    real_ip = request.headers.get("X-Real-IP","localhost")
    words_meaning_ids: list = json_data.meaning_ids
    callback_url = json_data.callback_url
    demo_name = json_data.demo_name
    student_stage = json_data.student_stage
    vocabulary = json_data.vocabulary
    class_id = json_data.class_id 

    try:
        if not words_meaning_ids:
            return resp_404(message="没有词义id")

        r = get_article.submit_task(words_meaning_ids=words_meaning_ids,callback_url=callback_url,
                                    real_ip=real_ip,demo_name=demo_name,
                                    student_stage=student_stage,vocabulary=vocabulary,class_id=class_id)
        return r if not isinstance(r,str) else resp_500(message=r)

    except Exception as e:
        logger.error(f"{type(e).__name__},{e}")
        return resp_500(message=f"{type(e).__name__},{e}")


@router.post("/query_oss_file")
def query_oss_file(json_data:dict,request:Request):
    oss_key = json_data.get("key")

    if not oss_key:
        return resp_500(message="请提供key值")
    j = query_file_content(key=oss_key)
    if j == 0:
        return resp_500(message="错误：没有这个文件")
    return JSONResponse(j)

