from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.config import settings
from app.database import engine, Base
from app.api import auth, vms, tunnel, admin, ssh_credentials
import logging

# 로깅 설정
logging.basicConfig(
    level=settings.LOG_LEVEL,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 라이프사이클 이벤트
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 시작 시
    logger.info("🚀 VConnect API 서버 시작")
    
    # DB 테이블 생성
    Base.metadata.create_all(bind=engine)
    
    # 관리자 계정 생성 (없으면)
    from app.services.auth_service import auth_service
    from app.database import SessionLocal
    from app.schemas.auth import UserRegister
    from app.models.user import UserRole
    
    db = SessionLocal()
    try:
        existing_admin = auth_service.get_user_by_username(db, settings.ADMIN_USERNAME)
        if not existing_admin:
            admin_data = UserRegister(
                username=settings.ADMIN_USERNAME,
                email=settings.ADMIN_EMAIL,
                password=settings.ADMIN_PASSWORD,
                full_name="Administrator"
            )
            admin_user = auth_service.register_user(db, admin_data)
            admin_user.role = UserRole.ADMIN
            db.commit()
            logger.info(f"✅ 관리자 계정 생성: {settings.ADMIN_USERNAME}")
    except Exception as e:
        logger.error(f"관리자 계정 생성 실패: {e}")
    finally:
        db.close()
    
    yield
    
    # 종료 시
    logger.info("🛑 VConnect API 서버 종료")

# FastAPI 앱 생성
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="Zero-Port, Zero-VPN SSH 기반 Proxmox VM 원격접속 플랫폼",
    lifespan=lifespan
)

# CORS 설정
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# API 라우터 등록
app.include_router(auth.router, prefix=f"{settings.API_V1_PREFIX}/auth", tags=["인증"])
app.include_router(vms.router, prefix=f"{settings.API_V1_PREFIX}/vms", tags=["VM 관리"])
app.include_router(tunnel.router, prefix=f"{settings.API_V1_PREFIX}/tunnel", tags=["터널 관리"])
app.include_router(admin.router, prefix=f"{settings.API_V1_PREFIX}/admin", tags=["관리자"])
app.include_router(ssh_credentials.router, prefix=f"{settings.API_V1_PREFIX}/ssh", tags=["SSH 자격증명"])

# Health Check
@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "app_name": settings.APP_NAME,
        "version": settings.APP_VERSION
    }

@app.get("/")
async def root():
    return {
        "message": "VConnect API Server",
        "version": settings.APP_VERSION,
        "docs": "/docs"
    }
