from fastapi import FastAPI, WebSocket, WebSocketDisconnect, BackgroundTasks
# 必须导入这一行
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
import asyncio
import os
from typing import Dict
# 修复playwright导入语法错误
from playwright.async_api import async_playwright

# 全局任务存储
tasks: Dict[str, dict] = {}
ws_connections: Dict[str, WebSocket] = {}

app = FastAPI(title="MD转PDF后端")


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 数据模型
class MDTaskReq(BaseModel):
    md_content: str
    header_text: str
    footer_tpl: str
    mt: int
    mb: int
    ml: int
    mr: int

# Windows 缓存目录
PDF_DIR = "d:/mdpdf/pdf_cache"
# 修复NameError: exist_ok → exist_ok=True
os.makedirs(PDF_DIR, exist_ok=True)

# 后台生成PDF
async def generate_pdf_task(task_id: str, req: MDTaskReq):
    task = tasks[task_id]
    task["status"] = "running"
    try:
        html_template = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
* {{font-family: "SimSun", "Microsoft YaHei", sans-serif;}}
.page-header {{text-align:center;font-size:13px;border-bottom:1px #ccc solid;padding-bottom:6px;margin-bottom:12px;}}
.page-footer {{text-align:center;font-size:12px;border-top:1px #ccc solid;padding-top:6px;margin-top:12px;}}
body {{padding:0 16px;line-height:1.8;}}
h1,h2,h3,h4 {{margin:16px 0 8px 0;}}
ul,ol {{padding-left:2.2em;}}
</style>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<div id="md-body"></div>
<script>
document.getElementById('md-body').innerHTML = marked.parse(`{req.md_content}`);
</script>
</body>
</html>
        """
        pdf_path = os.path.join(PDF_DIR, f"{task_id}.pdf")

        async with async_playwright() as p:
            browser = await p.chromium.launch(headless=True)
            page = await browser.new_page()
            await page.set_content(html_template)
            await page.wait_for_timeout(500)
            await page.pdf(
                path=pdf_path,
                format="A4",
                # 必须给页眉页脚预留足够物理边距,top建议≥15mm,bottom≥15mm
                margin={
                    "top": f"{req.mt}mm",
                    "bottom": f"{req.mb}mm",
                    "left": f"{req.ml}mm",
                    "right": f"{req.mr}mm"
                },
                display_header_footer=True,
                header_template="""
<div style="width:100%;box-sizing:border-box;text-align:center;font-size:13px;color:#333;padding:4px 8px;border-bottom:1px solid #cccccc;">
{{header}}
</div>""".replace("{{header}}", req.header_text),

                # 页脚模板:使用 class="pageNumber" / class="totalPages" 获取页码,不要 {{变量}}
                footer_template="""
<div style="width:100%;box-sizing:border-box;text-align:center;font-size:12px;color:#333;padding:4px 8px;border-top:1px solid #cccccc;">
{{footer}} 第 <span class="pageNumber"></span> 页 / 共 <span class="totalPages"></span> 页
</div>""".replace("{{footer}}", req.footer_tpl),

                print_background=True
            )
            await browser.close()

        task["status"] = "done"
        task["pdf_url"] = f"/pdf/{task_id}.pdf"
    except Exception as e:
        task["status"] = "fail"
        task["err"] = str(e)

    if task_id in ws_connections:
        ws = ws_connections[task_id]
        await ws.send_json({
            "task_id": task_id,
            "status": task["status"],
            "pdf_url": tasks[task_id].get("pdf_url", ""),
            "msg": "PDF生成完成" if task["status"] == "done" else f"生成失败:{task.get('err')}"
        })

# 提交任务接口
@app.post("/api/create-task")
async def create_task(req: MDTaskReq, bg: BackgroundTasks):
    task_id = str(uuid.uuid4())
    tasks[task_id] = {
        "status": "pending",
        "pdf_url": "",
        "err": ""
    }
    bg.add_task(generate_pdf_task, task_id, req)
    return {"task_id": task_id, "msg": "任务已提交"}

# WebSocket 长连接
@app.websocket("/ws/{task_id}")
async def ws_conn(websocket: WebSocket, task_id: str):
    await websocket.accept()
    ws_connections[task_id] = websocket
    try:
        while True:
            await websocket.receive_text()
    except WebSocketDisconnect:
        del ws_connections[task_id]

# 静态PDF访问
from fastapi.staticfiles import StaticFiles
app.mount("/pdf", StaticFiles(directory=PDF_DIR), name="pdf")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("mk-pdf:app", host="127.0.0.1", port=8000)