# -*- coding: utf-8 -*-

from fastapi import FastAPI, Form, HTTPException, Request, status, APIRouter, Query, Path, Depends, BackgroundTasks
from tools.loglog import logger, log_err_e

from core.respone_format import *
from gpt.get_article2 import GetArticle
from pydantic import BaseModel, ValidationError, conint, Field, conint
from typing import List, Optional, Literal
import asyncio

router = APIRouter()

get_article = GetArticle()


class Word(BaseModel):
    meaning_id: int = Field(..., description="单词的词义id")
    word_id: int = Field(..., description="单词id")
    spell: str = Field(..., description="单词的拼写")
    meaning: str = Field(..., description="单词的意思")


class ArticleRequest(BaseModel):
    core_words: List[Word] = Field(..., description="单词列表")
    take_count: int = 2
    demo_name: Optional[str] = "无"
    reading_level: conint(ge=1, le=30) = Field(default=10, description="阅读水平,默认值为10;[8,16,24]小学初中高中")
    article_length: int = Field(default=None, description="需要生成的文章长度,可以不传,不传自己根据reading_level判断")
    exercise_id: int = Field(default=0, description="学案ID,用于日志快速定位")


@router.post("/article/reading-comprehension")
def post_article(
        json_data: ArticleRequest,
        request: Request,
        background_tasks: BackgroundTasks,
):
    json_data = json_data.model_dump()
    real_ip = request.headers.get("X-Real-IP", "0.0.0.0")

    core_words = json_data["core_words"]
    take_count = json_data["take_count"]
    demo_name = json_data["demo_name"]
    reading_level = json_data["reading_level"]
    article_length = json_data["article_length"]
    exercise_id = json_data["exercise_id"]

    try:
        r = get_article.submit_task(
            real_ip=real_ip,
            core_words=core_words,
            take_count=take_count,
            demo_name=demo_name,
            reading_level=reading_level,
            article_length=article_length,
            exercise_id=exercise_id,
            background_tasks=background_tasks
        )
        return r if not isinstance(r, str) else resp_500(message=r)

    except Exception as e:
        log_err_e(e, msg="文章2接口错误/article/reading-comprehension;")
        return resp_500(message=f"{type(e).__name__},{e}")