"""Flask 文档问答应用：用 LangChain 完成加载、切分、向量检索与回答。"""
import os
import uuid
from pathlib import Path

from dotenv import load_dotenv
from flask import Flask, flash, redirect, render_template, request, url_for
from langchain_chroma import Chroma
from langchain_community.document_loaders import PyPDFLoader, TextLoader
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from werkzeug.utils import secure_filename

BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / ".env")
ALLOWED_EXTENSIONS = {".pdf", ".txt", ".md"}
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "10"))

app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "development-only-change-me")
app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_MB * 1024 * 1024
UPLOAD_DIR = BASE_DIR / "instance" / "uploads"
DB_DIR = BASE_DIR / "instance" / "chroma"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
DB_DIR.mkdir(parents=True, exist_ok=True)


def get_embeddings():
    """从环境变量构造兼容 OpenAI API 的 Embeddings 客户端。"""
    return OpenAIEmbeddings(
        model=os.getenv("EMBEDDING_MODEL", "text-embedding-3-small"),
        api_key=os.getenv("OPENAI_API_KEY", ""),
        base_url=os.getenv("OPENAI_BASE_URL") or None,
    )


def get_vector_store():
    """打开本地持久化 Chroma 集合。"""
    return Chroma(
        collection_name="course_documents",
        persist_directory=str(DB_DIR),
        embedding_function=get_embeddings(),
    )


def load_file(path: Path):
    """根据扩展名选择 PDF 或纯文本加载器。"""
    if path.suffix.lower() == ".pdf":
        return PyPDFLoader(str(path)).load()
    return TextLoader(str(path), encoding="utf-8", autodetect_encoding=True).load()


@app.get("/")
def index():
    """显示上传表单和知识库中的文件名。"""
    sources = []
    try:
        for item in get_vector_store().get(include=["metadatas"])["metadatas"] or []:
            source = item.get("source_name", "")
            if source and source not in sources:
                sources.append(source)
    except Exception:
        # 初次启动或尚未生成向量集合时显示空知识库。
        pass
    return render_template("index.html", sources=sources, max_upload_mb=MAX_UPLOAD_MB)


@app.post("/upload")
def upload():
    """保存上传文件、切分文本并将文本向量写入 Chroma。"""
    uploaded = request.files.get("document")
    if not uploaded or not uploaded.filename:
        flash("请选择一个文件。", "error")
        return redirect(url_for("index"))
    safe_name = secure_filename(uploaded.filename)
    suffix = Path(safe_name).suffix.lower()
    if suffix not in ALLOWED_EXTENSIONS:
        flash("仅支持 PDF、TXT 和 Markdown 文件。", "error")
        return redirect(url_for("index"))
    stored_path = UPLOAD_DIR / f"{uuid.uuid4().hex}_{safe_name}"
    try:
        uploaded.save(stored_path)
        documents = load_file(stored_path)
        documents = [doc for doc in documents if doc.page_content.strip()]
        if not documents:
            raise ValueError("文件没有可读取的文本内容。扫描版 PDF 请先进行 OCR。")
        for doc in documents:
            doc.metadata["source_name"] = safe_name
        chunks = RecursiveCharacterTextSplitter(
            chunk_size=800, chunk_overlap=120, add_start_index=True
        ).split_documents(documents)
        # 删除同名旧文档，避免重复上传造成检索结果重复。
        store = get_vector_store()
        old = store.get(where={"source_name": safe_name}, include=[])["ids"]
        if old:
            store.delete(ids=old)
        store.add_documents(chunks)
        flash(f"已处理 {safe_name}，切分为 {len(chunks)} 个文本块。", "success")
    except Exception as exc:
        stored_path.unlink(missing_ok=True)
        app.logger.exception("处理上传文档失败")
        flash(f"文档处理失败：{exc}", "error")
    return redirect(url_for("index"))


@app.post("/ask")
def ask():
    """检索相关文本块，再让聊天模型根据上下文回答。"""
    question = request.form.get("question", "").strip()
    if not question:
        flash("请先输入问题。", "error")
        return redirect(url_for("index"))
    try:
        store = get_vector_store()
        hits = store.similarity_search(question, k=4)
        if not hits:
            flash("知识库为空，请先上传文档。", "error")
            return redirect(url_for("index"))
        context = "\n\n".join(
            f"[来源：{doc.metadata.get('source_name', '未知')}，页码：{doc.metadata.get('page', '-')}]\n{doc.page_content}"
            for doc in hits
        )
        model = ChatOpenAI(
            model=os.getenv("CHAT_MODEL", "gpt-4o-mini"),
            api_key=os.getenv("OPENAI_API_KEY", ""),
            base_url=os.getenv("OPENAI_BASE_URL") or None,
            temperature=0.2,
        )
        response = model.invoke([
            ("system", "你是课程文档助手。只依据提供的资料回答；资料不足时明确说明，不要编造。回答使用中文，并在相关内容后标注来源文件和页码。"),
            ("human", f"资料：\n{context}\n\n问题：{question}"),
        ])
        answer = response.content if isinstance(response.content, str) else str(response.content)
        return render_template("answer.html", question=question, answer=answer, hits=hits)
    except Exception as exc:
        app.logger.exception("问答调用失败")
        flash(f"问答失败，请检查模型与 Embeddings 配置：{exc}", "error")
        return redirect(url_for("index"))


@app.errorhandler(413)
def too_large(_error):
    """把超出上传大小限制的请求转换成中文提示。"""
    flash(f"文件超过 {MAX_UPLOAD_MB} MB 上传限制。", "error")
    return redirect(url_for("index"))


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5008")), debug=True)
