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

import database
from services.models import Account
from services.state import safe_get_user_accounts_snapshot, safe_set_user_accounts


def load_user_accounts(user_id: int) -> None:
    """从数据库加载用户的账号到内存（保持原逻辑不变）。"""
    existing_accounts = safe_get_user_accounts_snapshot(user_id)
    accounts_by_id = {}
    accounts_data = database.get_user_accounts(user_id)
    for acc_data in accounts_data:
        account_id = acc_data["id"]
        existing = existing_accounts.get(account_id)
        if isinstance(existing, Account):
            existing.username = acc_data["username"]
            existing._password = acc_data["password"]
            existing.remember = bool(acc_data["remember"])
            existing.remark = acc_data["remark"] or ""
            accounts_by_id[existing.id] = existing
            continue

        account = Account(
            account_id=account_id,
            user_id=user_id,
            username=acc_data["username"],
            password=acc_data["password"],
            remember=bool(acc_data["remember"]),
            remark=acc_data["remark"] or "",
        )
        accounts_by_id[account.id] = account

    safe_set_user_accounts(user_id, accounts_by_id)
