# -*- coding: utf-8 -*-
"""
auth.py — 认证与页面路由

从原 server.py 迁入：login / logout / get_user_info / index。
@app.route → @bp.route。
"""

from datetime import datetime

from flask import Blueprint, request, jsonify, render_template, session, redirect

import container
from auth import user_manager
from decorators import login_required
from utils.audit import log_audit
from utils.response import error_response
from utils.error_codes import ErrorCodes
from utils.logger import get_logger

logger = get_logger(__name__)

bp = Blueprint('auth', __name__)


@bp.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if request.method == 'GET':
        # 已登录则直接跳转
        if 'user' in session:
            next_url = request.args.get('next', '/')
            # 安全校验：仅允许本站相对路径
            if not next_url.startswith('/') or next_url.startswith('//'):
                next_url = '/'
            return redirect(next_url)
        next_url = request.args.get('next', '')
        return render_template('login.html', next_url=next_url)

    # POST 请求：处理登录
    data = request.get_json() or {}
    username = data.get('username', '').strip()
    password = data.get('password', '').strip()
    remember = data.get('remember', False)

    if not username or not password:
        return jsonify(error_response(ErrorCodes.INVALID_PARAM, '用户名和密码不能为空')), 400

    # 验证登录
    user = user_manager.authenticate(username, password)

    if user:
        # 创建 Session
        session['user'] = {
            'id': user['id'],
            'username': user['username'],
            'role': user['role']
        }

        if remember:
            session.permanent = True

        # 记录审计日志
        log_audit({
            'timestamp': datetime.now().isoformat(),
            'user': username,
            'role': user['role'],
            'action': 'login',
            'ip': request.remote_addr,
            'result': 'success'
        })

        # next 参数回跳
        next_url = request.args.get('next') or data.get('next') or '/'
        # 安全校验：仅允许本站相对路径
        if not next_url.startswith('/') or next_url.startswith('//'):
            next_url = '/'

        return jsonify({
            'success': True,
            'user': session['user'],
            'next': next_url,
        })
    else:
        # 记录失败日志
        log_audit({
            'timestamp': datetime.now().isoformat(),
            'user': username,
            'action': 'login',
            'ip': request.remote_addr,
            'result': 'failed'
        })

        return jsonify(error_response(ErrorCodes.UNAUTHORIZED, '用户名或密码错误，或账号已被锁定')), 401


@bp.route('/logout', methods=['POST'])
def logout():
    """注销登录"""
    user = session.get('user', {})

    # 记录审计日志
    if user:
        log_audit({
            'timestamp': datetime.now().isoformat(),
            'user': user.get('username'),
            'role': user.get('role'),
            'action': 'logout',
            'ip': request.remote_addr,
            'result': 'success'
        })

    session.clear()
    return jsonify({'success': True})


@bp.route('/api/user/info', methods=['GET'])
@login_required
def get_user_info():
    """获取当前用户信息"""
    return jsonify({
        'success': True,
        'user': session.get('user')
    })
