from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from pydantic import BaseModel

from app.api.v1 import deps
from app.services.captcha_service import CaptchaService
from app.services.sms_service import SmsService
from app.models.user import User, UserRole, UserStatus
from app.core import security

router = APIRouter()

class CaptchaResponse(BaseModel):
    captcha_id: str
    image: str
    expire_seconds: int

class SystemStatus(BaseModel):
    initialized: bool

class SetupAdminRequest(BaseModel):
    mobile: str
    sms_code: str
    password: str

@router.get("/captcha", response_model=CaptchaResponse, summary="获取验证码")
def get_captcha():
    """
    生成新的图形验证码。
    """
    try:
        return CaptchaService.generate_captcha()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/init-status", response_model=SystemStatus, summary="获取初始化状态")
def get_init_status(db: Session = Depends(deps.get_db)):
    """
    检查系统是否已初始化（是否存在用户）。
    """
    user = db.query(User).first()
    return {"initialized": bool(user)}

@router.post("/setup-admin", summary="设置超级管理员")
def setup_admin(
    req: SetupAdminRequest,
    db: Session = Depends(deps.get_db)
):
    """
    创建第一个超级管理员用户。仅在系统无用户时可用。
    """
    # 1. Check if already initialized
    if db.query(User).first():
        raise HTTPException(status_code=400, detail="系统已初始化")

    # 2. Verify SMS
    if not SmsService.verify_code(req.mobile, req.sms_code):
        raise HTTPException(status_code=400, detail="短信验证码无效")

    # 3. Create Admin User
    db_user = User(
        mobile=req.mobile,
        password_hash=security.get_password_hash(req.password),
        status=UserStatus.ACTIVE,
        role=UserRole.SUPER_ADMIN
    )
    db.add(db_user)
    db.commit()
    return {"message": "超级管理员创建成功"}
