"""FastAPI application entry point."""

import logging
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles

from controller.manager import PipelineManager
from web.router import create_router
from web.services import WebService

logger = logging.getLogger(__name__)

# 项目根目录（用于 config 等，app.py 在 src/web/ 下）
project_root = Path(__file__).resolve().parent.parent.parent
# Web 界面相关目录统一放在 src/web/ 下
_web_dir = Path(__file__).resolve().parent
frontend_dir = _web_dir / "frontend"
static_dir = _web_dir / "static"

# 创建 FastAPI 应用
app = FastAPI(
    title="Co-location MVP Web API",
    description="Web interface for interactive co-location pattern mining with Stage3 preference learning",
    version="1.0.0"
)

# 全局变量存储服务实例
service: WebService = None


@app.on_event("startup")
async def startup_event():
    """Initialize services on startup."""
    global service
    
    # 初始化 PipelineManager
    config_path = project_root / "config" / "config.yaml"
    manager = PipelineManager(config_path=str(config_path))
    
    # 创建 WebService
    service = WebService(manager)
    
    # 创建并挂载路由
    router = create_router(service)
    app.include_router(router)
    
    logger.info("Web service initialized successfully")


# 挂载静态文件目录
if static_dir.exists():
    app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")


@app.get("/", response_class=HTMLResponse)
async def index():
    """Serve the main HTML page."""
    index_path = frontend_dir / "index.html"
    if index_path.exists():
        with open(index_path, 'r', encoding='utf-8') as f:
            return HTMLResponse(content=f.read())
    else:
        return HTMLResponse(content="""
        <!DOCTYPE html>
        <html>
        <head>
            <title>iCoLoc</title>
            <meta charset="utf-8">
        </head>
        <body>
            <h1>Co-location MVP Web Interface</h1>
            <p>Frontend files not found. Please create frontend/index.html</p>
        </body>
        </html>
        """)


@app.get("/health")
async def health():
    """Health check endpoint."""
    return {"status": "ok", "message": "Service is running"}


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

