"""
Playwright RPA 执行器 - FastAPI 应用

基于 FastAPI + APScheduler 的现代化执行器架构：
- FastAPI: 提供健康检查和监控接口
- APScheduler: 管理浏览器池定时清理任务
- SnailJob: 分布式任务调度

使用方式:
    # 本地运行
    python main.py
    # 或
    uvicorn main:app --host 0.0.0.0 --port 8000

    # Docker 运行
    docker run -e GIT_TOKEN=xxx snail-job-playwright

    # Docker Compose
    docker-compose up -d
"""
import threading
from contextlib import asynccontextmanager

from fastapi import FastAPI

from snailjob import ExecutorManager, client_main
from executor.executor import playwright_executor
from executor.logger import logger
from routes.download import router as download_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """FastAPI 生命周期管理"""
    
    # ========== 启动阶段 ==========
    logger.LOCAL.info("=" * 60)
    logger.LOCAL.info("🚀 Playwright RPA 执行器服务启动")
    
    # 2. 注册 Playwright 执行器
    ExecutorManager.register(playwright_executor)
    logger.LOCAL.info("✅ Playwright 执行器已注册")
    
    # 3. 启动 SnailJob 客户端（在后台线程）
    def run_snailjob_client():
        try:
            client_main()
        except Exception as e:
            logger.LOCAL.error(f"❌ SnailJob 客户端异常: {e}")
    
    client_thread = threading.Thread(target=run_snailjob_client, daemon=True)
    client_thread.start()
    logger.LOCAL.info("✅ SnailJob 客户端已启动")
    
    logger.LOCAL.info("=" * 60)
    logger.LOCAL.info("🎉 所有服务启动完成")
    logger.LOCAL.info(f"📍 监控地址: http://0.0.0.0:8000")
    logger.LOCAL.info("=" * 60)
    
    yield  # 应用运行中
    
    # ========== 关闭阶段 ==========
    logger.LOCAL.info("🛑 执行器服务已关闭")


# 创建 FastAPI 应用
app = FastAPI(
    title="Playwright RPA Executor",
    description="基于 SnailJob 的 Playwright 自动化执行器",
    lifespan=lifespan
)

# 注册路由
app.include_router(download_router)


@app.get("/health")
async def health():
    """详细健康检查"""
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn
    
    # 使用 uvicorn 启动
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_level="info"
    )