"""
表格线编辑器后端服务
FastAPI 应用入口
"""

import sys
from pathlib import Path

# 添加 ocr_platform 根目录到 Python 路径（必须在导入其他模块之前）
_file_path = Path(__file__).resolve()
ocr_platform_root = _file_path.parents[2]  # main.py -> backend -> table_line_generator -> ocr_platform
if str(ocr_platform_root) not in sys.path:
    sys.path.insert(0, str(ocr_platform_root))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

# 配置日志
logger.remove()
logger.add(
    sys.stdout,
    level="INFO",
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
)

# 创建应用
app = FastAPI(
    title="表格线编辑器 API",
    description="无线表格智能标注工具后端服务",
    version="0.1.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",  # Vite 开发服务器
        "http://localhost:3000",  # 备用端口
        "http://127.0.0.1:5173",
        "http://127.0.0.1:3000",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
from api.editor import router as editor_router
from api.template import router as template_router
from api.directory import router as directory_router
from api.config import router as config_router
from api.batch import router as batch_router

app.include_router(editor_router)
app.include_router(template_router)
app.include_router(directory_router)
app.include_router(config_router)
app.include_router(batch_router)


@app.get("/")
async def root():
    """根路径"""
    return {
        "service": "table-line-editor",
        "version": "0.1.0",
        "docs": "/docs"
    }


@app.on_event("startup")
async def startup_event():
    logger.info("🚀 表格线编辑器后端服务启动")
    logger.info("📚 API 文档: http://localhost:8000/docs")


@app.on_event("shutdown")
async def shutdown_event():
    logger.info("👋 表格线编辑器后端服务关闭")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )
