import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn

from database.database import engine, get_db
from database.models import Base
from routers import auth, issues, reports, projects, page_permissions, inbox, management
from services.auth_service import create_admin_user

# 데이터베이스 테이블 생성 (sso_users, projects는 이미 존재하므로 제외)
tables_to_create = [
    table for name, table in Base.metadata.tables.items()
    if name not in ("sso_users", "projects")
]
Base.metadata.create_all(bind=engine, tables=tables_to_create)

# 앱 시작/종료 lifecycle
@asynccontextmanager
async def lifespan(app: FastAPI):
    db = next(get_db())
    create_admin_user(db)
    db.close()
    yield

# FastAPI 앱 생성
app = FastAPI(
    title="M-Project API",
    description="작업보고서 시스템 API",
    version="1.0.0",
    lifespan=lifespan
)

ALLOWED_ORIGINS = [
    "https://tkfb.technicalkorea.net",
    "https://tkreport.technicalkorea.net",
    "https://tkqc.technicalkorea.net",
    "https://tkuser.technicalkorea.net",
]
if os.getenv("ENV", "production") == "development":
    ALLOWED_ORIGINS += ["http://localhost:30080", "http://localhost:30180", "http://localhost:30280"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["*"]
)

# 라우터 등록
app.include_router(auth.router)
app.include_router(issues.router)
app.include_router(inbox.router)  # 수신함 라우터 추가
app.include_router(reports.router)
app.include_router(projects.router)
app.include_router(page_permissions.router)
app.include_router(management.router)  # 관리함 라우터 추가

# 루트 엔드포인트
@app.get("/")
async def root():
    return {"message": "M-Project API", "version": "1.0.0"}

# 헬스체크
@app.get("/api/health")
async def health_check():
    return {"status": "healthy"}

# 전역 예외 처리
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    import traceback
    traceback.print_exc()
    return JSONResponse(
        status_code=500,
        content={"detail": "서버 오류가 발생했습니다"}
    )

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