from fastapi import APIRouter, Depends, Query, Request
from ...core.database import get_db
from ...core.permission import require_login
from ...core.wiki_config import get_wiki_feedback_config
from ...utils.request_utils import safe_json
import json
import datetime

router = APIRouter()


@router.post("/ai/save-to-wiki")
async def save_to_wiki(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    conn, cur = db
    body = await safe_json(request)

    content = body.get("content")
    wiki_config = await get_wiki_feedback_config()
    min_len = wiki_config["min_content_length"]
    max_len = wiki_config["max_content_length"]

    if not content or len(content.strip()) < min_len:
        return {"error": f"反哺内容不能少于{min_len}个字", "detail": "content too short"}

    if len(content) > max_len:
        return {"error": f"内容过长，最大支持{max_len}字", "detail": "content too long"}

    user_id = int(user["userId"]) if user["userId"].isdigit() else 1
    title_format = wiki_config["title_format"]
    default_title = title_format.replace("{date}", datetime.date.today().strftime('%Y/%m/%d'))
    title = (body.get("title") or "").strip() or default_title
    dir_id = int(body["directory_id"]) if body.get("directory_id") else None
    tags_json = json.dumps(body["tags"]) if body.get("tags") else None

    await cur.execute(
        "INSERT INTO wiki_feedback (message_id, thread_id, submitted_by, title, content, suggested_directory_id, suggested_tags, status) "
        "VALUES (%s, %s, %s, %s, %s, %s, %s, 'pending_review')",
        (body.get("message_id"), body.get("thread_id"), user_id, title, content, dir_id, tags_json),
    )
    feedback_id = cur.lastrowid

    return {"success": True, "message": "知识反哺已提交，等待审核", "data": {"id": feedback_id, "status": "pending_review"}}


