import threading
import time
import webbrowser

import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from typer import Typer

from mineru_flow.internal.middleware import add_middleware
from mineru_flow.alembic.run_migrate import run_db_migrations
from mineru_flow.internal.api import initial_routers
from mineru_flow.internal.common.db import init_tables
from mineru_flow.internal.common.exceptions import add_exception_handler
from mineru_flow.internal.common.logging import get_logger, setup_logging
from mineru_flow.internal.config.config import settings
from mineru_flow.internal.worker.simple_manager import (
    start_simple_workers,
    stop_simple_workers,
)
from mineru_flow.version import version

app = FastAPI(
    title="mineru-flow",
    description="mineru-flow",
    version=version,
    terms_of_service="",
    contact={
        "name": "mineru-flow",
        "url": "https://github.com/OpenDataLab/mineru-flow",
        "email": "shenguanlin@pjlab.org.cn",
    },
    license_info={
        "name": "Apache 2.0",
        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
    },
)

setup_logging(
    log_level=settings.LOG_LEVEL,
    log_file=settings.LOG_FILE,
    enable_json=settings.LOG_JSON,
)
app_logger = get_logger("app")

init_tables()
run_db_migrations()
initial_routers(app)
add_middleware(app)
add_exception_handler(app)

app.mount("", StaticFiles(packages=["mineru_flow.internal"], html=True))


@app.on_event("startup")
async def startup_event():
    """应用启动时启动 Worker 系统"""
    app_logger.info("🚀 启动应用和 Worker 系统...")
    try:
        await start_simple_workers()
        app_logger.info("✅ Worker 系统启动成功")
    except Exception as e:
        app_logger.error("❌ Worker 系统启动失败", error=str(e))


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时停止 Worker 系统"""
    app_logger.info("🛑 正在关闭 Worker 系统...")
    try:
        await stop_simple_workers()
        app_logger.info("✅ Worker 系统关闭完成")
    except Exception as e:
        app_logger.error("❌ Worker 系统关闭异常", error=str(e))


cli = Typer()


@cli.callback(invoke_without_command=True)
def main(host: str = "localhost", port: int = 8000, open: bool = False):
    if port:
        settings.PORT = str(port)  # 确保PORT是字符串
    if host:
        settings.HOST = host

    if open:

        def open_browser():
            time.sleep(2)
            url = f"http://{settings.HOST}:{settings.PORT}"
            app_logger.info("打开浏览器", url=url)
            webbrowser.open(url)

        # 在后台线程中打开浏览器
        browser_thread = threading.Thread(target=open_browser)
        browser_thread.daemon = True
        browser_thread.start()

    app_logger.info(
        "启动 HTTP 服务", host=settings.HOST, port=settings.PORT, auto_open=open
    )
    uvicorn.run(app=app, host=settings.HOST, port=int(settings.PORT))


if __name__ == "__main__":
    cli()
