"""
시스템 초기 설정 API
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from pydantic import BaseModel, EmailStr
from typing import Optional

from ...core.database import get_db
from ...core.security import get_password_hash
from ...models.user import User

router = APIRouter()


class InitialSetupRequest(BaseModel):
    """초기 설정 요청"""
    admin_email: EmailStr
    admin_password: str
    admin_full_name: Optional[str] = None


class SetupStatusResponse(BaseModel):
    """설정 상태 응답"""
    is_setup_required: bool
    has_admin_user: bool
    total_users: int


@router.get("/status", response_model=SetupStatusResponse)
async def get_setup_status(db: AsyncSession = Depends(get_db)):
    """시스템 설정 상태 확인"""
    # 전체 사용자 수 조회
    total_users_result = await db.execute(select(func.count(User.id)))
    total_users = total_users_result.scalar()
    
    # 관리자 사용자 존재 여부 확인
    admin_result = await db.execute(
        select(User).where(User.role == "root")
    )
    has_admin_user = admin_result.scalar_one_or_none() is not None
    
    return SetupStatusResponse(
        is_setup_required=total_users == 0 or not has_admin_user,
        has_admin_user=has_admin_user,
        total_users=total_users
    )


@router.post("/initialize")
async def initialize_system(
    setup_data: InitialSetupRequest,
    db: AsyncSession = Depends(get_db)
):
    """시스템 초기 설정 (root 계정 생성)"""
    # 이미 설정된 시스템인지 확인
    existing_admin = await db.execute(
        select(User).where(User.role == "root")
    )
    if existing_admin.scalar_one_or_none():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="System is already initialized"
        )
    
    # 이메일 중복 확인
    existing_user = await db.execute(
        select(User).where(User.email == setup_data.admin_email)
    )
    if existing_user.scalar_one_or_none():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email already registered"
        )
    
    # Root 관리자 계정 생성
    hashed_password = get_password_hash(setup_data.admin_password)
    
    admin_user = User(
        email=setup_data.admin_email,
        hashed_password=hashed_password,
        full_name=setup_data.admin_full_name or "시스템 관리자",
        is_active=True,
        is_admin=True,
        role="root",
        can_manage_books=True,
        can_manage_notes=True,
        can_manage_novels=True
    )
    
    db.add(admin_user)
    await db.commit()
    await db.refresh(admin_user)
    
    return {
        "message": "System initialized successfully",
        "admin_user": {
            "id": str(admin_user.id),
            "email": admin_user.email,
            "full_name": admin_user.full_name,
            "role": admin_user.role
        }
    }
