# -*- coding: utf-8 -*-
"""
auth.py — 用户认证模块

功能：
  - 用户登录验证
  - 密码加密与验证
  - Session 管理
  - 用户数据读写
  - 防暴力破解保护
"""

import os
import json
import time
from pathlib import Path
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

# 用户数据文件路径
USERS_FILE = Path(__file__).parent / "users.json"

# 登录失败记录（防暴力破解）
login_attempts = {}  # {"username": {"count": 0, "lock_until": 0}}


class UserManager:
    """用户管理器"""

    def __init__(self):
        self.users = self._load_users()

    def _load_users(self):
        """加载用户数据"""
        if not USERS_FILE.exists():
            # 创建默认管理员账号
            default_users = {
                "users": [{
                    "id": 1,
                    "username": "admin",
                    "password_hash": generate_password_hash("Admin@2026"),
                    "role": "admin",
                    "created_at": datetime.now().isoformat(),
                    "last_login": None,
                    "login_count": 0,
                    "active": True
                }]
            }
            self._save_users(default_users)
            return default_users

        with open(USERS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)

    def _save_users(self, data):
        """保存用户数据"""
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def authenticate(self, username, password):
        """
        验证用户登录

        Returns:
          成功：用户字典
          失败：None
        """
        # 检查账号是否被锁定
        if self._is_locked(username):
            return None

        # 查找用户
        user = None
        for u in self.users.get('users', []):
            if u['username'] == username:
                user = u
                break

        if not user:
            self._record_failed_login(username)
            return None

        # 检查账号是否激活
        if not user.get('active', True):
            return None

        # 验证密码
        if check_password_hash(user['password_hash'], password):
            # 登录成功，清除失败记录
            if username in login_attempts:
                del login_attempts[username]

            # 更新登录信息
            user['last_login'] = datetime.now().isoformat()
            user['login_count'] = user.get('login_count', 0) + 1
            self._save_users(self.users)

            return user
        else:
            # 登录失败，记录
            self._record_failed_login(username)
            return None

    def _is_locked(self, username):
        """检查账号是否被锁定"""
        if username not in login_attempts:
            return False

        attempts = login_attempts[username]
        if attempts['count'] >= 5:
            # 检查锁定是否过期（15分钟）
            if time.time() < attempts['lock_until']:
                return True
            else:
                # 锁定过期，清除记录
                del login_attempts[username]
                return False

        return False

    def _record_failed_login(self, username):
        """记录登录失败"""
        if username not in login_attempts:
            login_attempts[username] = {'count': 0, 'lock_until': 0}

        login_attempts[username]['count'] += 1

        # 失败5次后锁定15分钟
        if login_attempts[username]['count'] >= 5:
            login_attempts[username]['lock_until'] = time.time() + 900  # 15分钟

    def get_user(self, username):
        """获取用户信息"""
        for u in self.users.get('users', []):
            if u['username'] == username:
                return u
        return None

    def get_user_by_id(self, user_id):
        """通过ID获取用户"""
        for u in self.users.get('users', []):
            if u['id'] == user_id:
                return u
        return None

    def add_user(self, username, password, role='user'):
        """添加新用户"""
        # 检查用户名是否已存在
        if self.get_user(username):
            return False

        new_user = {
            "id": len(self.users['users']) + 1,
            "username": username,
            "password_hash": generate_password_hash(password),
            "role": role,
            "created_at": datetime.now().isoformat(),
            "last_login": None,
            "login_count": 0,
            "active": True
        }

        self.users['users'].append(new_user)
        self._save_users(self.users)
        return True

    def update_password(self, username, new_password):
        """修改密码"""
        user = self.get_user(username)
        if not user:
            return False

        user['password_hash'] = generate_password_hash(new_password)
        self._save_users(self.users)
        return True

    def toggle_user_active(self, username, active):
        """启用/禁用用户"""
        user = self.get_user(username)
        if not user:
            return False

        user['active'] = active
        self._save_users(self.users)
        return True

    def get_all_users(self):
        """获取所有用户列表"""
        return self.users.get('users', [])


# 全局用户管理器实例
user_manager = UserManager()
