/**
 * 悬浮窗交易草稿管理（App 后台模式的浮窗入账）。
 *
 * 从 automationPipeline.ts 提取，职责：
 * - 管理待确认的交易草稿 Map（LRU + 2 分钟超时）
 * - 构建浮窗排序数据（分类和账户按历史频次排序）
 */

import { useMetadataStore } from '../../store/metadataStore';
import type { ImportedEvent, LedgerIndex, TransactionDraft } from '../../domain/core/types';
import { logger } from '../../utils/logger';
import { dedupFingerprint } from '../../domain/transaction/dedup';
import { removeProcessedTxKey } from '../security/txKeyStore';

export interface PendingDraft {
  draft: TransactionDraft;
  event: ImportedEvent;
}

export const pendingDrafts = new Map<string, PendingDraft>();

/** pendingDrafts 最大容量，超出时清理最旧的条目。 */
const PENDING_DRAFTS_MAX = 50;

export function evictOldestPendingDraft(): void {
  if (pendingDrafts.size <= PENDING_DRAFTS_MAX) return;
  const oldestKey = pendingDrafts.keys().next().value;
  if (oldestKey) {
    const evicted = pendingDrafts.get(oldestKey);
    pendingDrafts.delete(oldestKey);
    // 同步清除去重键，避免被驱逐的交易永久阻断重新触发
    if (evicted) {
      const txKey = dedupFingerprint(evicted.event);
      removeProcessedTxKey(txKey);
    }
    logger.warn('floatingBillManager', `[浮窗草稿驱逐] 容量超限(${PENDING_DRAFTS_MAX})，清理最旧草稿: ${oldestKey}`);
  }
}

/**
 * 构建悬浮窗排序数据（分类和账户按历史频次排序）。
 */
export function buildFloatingBillData(
  targetAccount: string,
  sourceAccount: string,
  ledger: LedgerIndex,
) {
  const transactions = ledger.transactions;
  const categoryFreq: Record<string, number> = {};
  const accountFreq: Record<string, number> = {};

  for (const tx of transactions.slice(-50)) {
    for (const posting of tx.postings) {
      const acct = posting.account;
      if (acct.startsWith('Expenses:') || acct.startsWith('Income:')) {
        categoryFreq[acct] = (categoryFreq[acct] || 0) + 1;
      } else if (acct.startsWith('Assets:') || acct.startsWith('Liabilities:')) {
        accountFreq[acct] = (accountFreq[acct] || 0) + 1;
      }
    }
  }

  const categories = useMetadataStore.getState().categories;
  const sortedCategories = [...categories].map(cat => {
    let score = categoryFreq[cat.linkedAccount] || 0;
    if (cat.linkedAccount === targetAccount) score += 1000;
    return { id: cat.id, name: cat.name, account: cat.linkedAccount, type: cat.type, score };
  }).sort((a, b) => b.score - a.score)
    .map(({ id, name, account, type }) => ({ id, name, account, type }));

  let assetAccounts = Array.from(ledger.accounts.keys()).filter((a: string) => a.startsWith('Assets') || a.startsWith('Liabilities'));
  if (assetAccounts.length === 0) {
    assetAccounts = ['Assets:支付宝余额', 'Assets:微信零钱', 'Assets:现金'];
  }
  const sortedAccounts = assetAccounts.map((acct: string) => {
    let score = accountFreq[acct] || 0;
    if (acct === sourceAccount) score += 1000;
    return { acct, score };
  }).sort((a, b) => b.score - a.score)
    .map(({ acct }) => acct);

  return { sortedCategories, sortedAccounts };
}
