#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

from flask_login import current_user
from flask_socketio import emit, join_room, leave_room

from services.accounts_service import load_user_accounts
from services.client_log import log_to_client
from services.state import safe_get_user_accounts_snapshot, safe_get_user_logs


def register_socketio_handlers(socketio) -> None:
    @socketio.on("connect")
    def handle_connect():
        """客户端连接"""
        if current_user.is_authenticated:
            user_id = current_user.id
            join_room(f"user_{user_id}")
            log_to_client("客户端已连接", user_id)

            accounts = safe_get_user_accounts_snapshot(user_id)
            if not accounts:
                load_user_accounts(user_id)
                accounts = safe_get_user_accounts_snapshot(user_id)

            emit("accounts_list", [acc.to_dict() for acc in accounts.values()])

            for log_entry in safe_get_user_logs(user_id):
                emit("log", log_entry)

    @socketio.on("disconnect")
    def handle_disconnect():
        """客户端断开"""
        if current_user.is_authenticated:
            user_id = current_user.id
            leave_room(f"user_{user_id}")

