"""
密码管理 API — 单机版（V3.0+ 精简版）

V3.0 变更：
- user.db 不再使用 SQLCipher 加密，改为明文 SQLite
- 本模块保留 API 兼容性，但大部分操作已简化为空操作或缓存管理
- 密码功能保留用于未来可能的扩展（如文件加密密码）
"""
import logging
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional

from ...core.database import get_db, get_system_db, get_user_db, _has_split_databases
from ...core import crypto

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/admin/password", tags=["密码管理"])


class SetPasswordRequest(BaseModel):
    password: str
    confirm_password: str


class ChangePasswordRequest(BaseModel):
    old_password: str
    new_password: str
    confirm_password: str


class UnlockRequest(BaseModel):
    password: str


@router.get("/status")
async def get_password_status():
    """
    获取密码状态

    V3.0+ 变更：user.db 始终为明文，db_encrypted 固定返回 false
    """
    from ...core.password_store import has_stored_password
    stored_pwd = crypto.get_password()

    return {
        "has_password": has_stored_password(),
        "is_unlocked": stored_pwd is not None,
        "db_encrypted": False,  # V3.0+ user.db 不再加密
    }


@router.post("/set")
async def set_password(req: SetPasswordRequest):
    """
    设置密码（V3.0+ 简化：仅缓存密码，不再加密 user.db）

    保留接口兼容性，前端可继续调用。
    """
    if req.password != req.confirm_password:
        raise HTTPException(status_code=400, detail="两次密码不一致")

    if len(req.password) < 6:
        raise HTTPException(status_code=400, detail="密码长度不能少于6位")

    from ...core.password_store import save_password_cross_platform

    # 缓存密码到进程内存
    crypto.set_password(req.password)

    # 保存到安全存储
    try:
        save_password_cross_platform(req.password)
    except Exception as e:
        logger.warning(f"密码保存到安全存储失败: {e}")

    return {"message": "密码设置成功"}


@router.post("/change")
async def change_password(req: ChangePasswordRequest):
    """
    修改密码（V3.0+ 简化：仅更新缓存和存储，不再执行 SQLCipher rekey）
    """
    if req.new_password != req.confirm_password:
        raise HTTPException(status_code=400, detail="两次新密码不一致")

    if len(req.new_password) < 6:
        raise HTTPException(status_code=400, detail="密码长度不能少于6位")

    # 验证旧密码
    current_password = crypto.get_password()
    if current_password and current_password != req.old_password:
        raise HTTPException(status_code=400, detail="旧密码错误")

    from ...core.password_store import load_password_cross_platform, save_password_cross_platform

    if not current_password:
        stored = load_password_cross_platform()
        if stored and stored != req.old_password:
            raise HTTPException(status_code=400, detail="旧密码错误")

    # 更新密码缓存（不再需要 rekey user.db）
    crypto.set_password(req.new_password)

    # 更新安全存储
    try:
        save_password_cross_platform(req.new_password)
    except Exception as e:
        logger.warning(f"密码更新到安全存储失败: {e}")

    return {"message": "密码修改成功"}


@router.post("/unlock")
async def unlock_database(req: UnlockRequest):
    """
    解锁（V3.0+ 简化：仅验证并缓存密码，不再验证 user.db 加密）
    """
    from ...core.password_store import load_password_cross_platform

    # 验证密码
    stored = load_password_cross_platform()
    if stored and stored != req.password:
        raise HTTPException(status_code=401, detail="密码错误")

    # 缓存密码
    crypto.set_password(req.password)

    return {"message": "解锁成功"}


@router.post("/clear")
async def clear_password(admin_password: Optional[str] = None):
    """清除密码（管理员重置）"""
    crypto.clear_password()

    from ...core.password_store import clear_password as clear_stored
    try:
        clear_stored()
    except Exception as e:
        logger.warning(f"清除密码存储失败: {e}")

    return {"message": "密码已清除，下次启动需要重新设置"}


@router.post("/auto-unlock")
async def auto_unlock():
    """
    自动解锁（启动时调用）

    V3.0+ 变更：user.db 为明文，无需解锁数据库。
    仅尝试从安全存储恢复密码缓存以保持兼容性。
    """
    # 检查是否已解锁
    if crypto.get_password():
        return {"message": "已解锁", "auto": True}

    # 尝试从安全存储加载
    from ...core.password_store import load_password_cross_platform
    password = load_password_cross_platform()

    if password:
        crypto.set_password(password)

    return {"message": "自动解锁成功", "auto": True}
