#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证相关路由
"""

from flask import Blueprint, render_template, request, redirect, url_for, session, flash, jsonify
from services.auth_service import authenticate_user, check_clinic_access

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/')
def index():
    """首页 - 重定向到登录页面"""
    return redirect(url_for('auth.login'))

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # 验证用户
        auth_result = authenticate_user(username, password)
        
        if auth_result['success']:
            user = auth_result['user']
            session['user'] = user
            session['username'] = user['username']
            session['real_name'] = user['real_name']
            session['role'] = user['role']
            session['clinic_id'] = user['clinic_id']
            session['clinic_name'] = user['clinic_name']

            print(f"✅ 用户 {user['real_name']} ({user['username']}) 登录成功")
            flash(f'欢迎，{user["real_name"]}！', 'success')

            # 根据用户角色重定向
            if user['role'] == 'admin':
                # 管理员重定向到管理员仪表板
                return redirect(url_for('patient.admin_dashboard'))
            else:
                # 普通用户重定向到患者列表页面（原版行为）
                return redirect(url_for('patient.patient_list_original', clinic_id=user['clinic_id']))
        else:
            flash(auth_result['message'], 'error')
    
    return render_template('login.html')

@auth_bp.route('/logout')
def logout():
    """退出登录"""
    username = session.get('real_name', '未知用户')
    session.clear()
    print(f"✅ 用户 {username} 退出登录")
    flash('已成功退出登录', 'info')
    return redirect(url_for('auth.login'))

@auth_bp.route('/api/check-session', methods=['GET'])
def check_session():
    """检查会话状态API"""
    if 'user' in session:
        return jsonify({
            'logged_in': True,
            'user': {
                'username': session.get('username'),
                'real_name': session.get('real_name'),
                'role': session.get('role'),
                'clinic_name': session.get('clinic_name')
            }
        })
    else:
        return jsonify({'logged_in': False})
