/**
 * postings → 「双腿」解析（NumpadSheet 编辑/草稿预填用）。
 * 是 buildPostings 的逆操作：从一组分录推断方向、资金账户、目标账户与绝对值金额。
 */
import type { Posting } from '../core/types';

export interface TransactionLegs {
  direction: 'expense' | 'income' | 'transfer';
  /** 资金腿（Assets/Liabilities）；转账时为转出方。 */
  sourceAccount: string;
  /** 分类账户（Expenses/Income）或转账的目标资金账户。 */
  targetAccount: string;
  /** 绝对值金额（无负号）。 */
  amount: string;
  currency: string;
}

function isAssetLike(account: string): boolean {
  return account.startsWith('Assets') || account.startsWith('Liabilities');
}

function abs(amount: string | undefined): string {
  return (amount ?? '').replace(/^-/, '');
}

/**
 * 从分录推断双腿；无法识别时返回 null。
 * 仅接受恰好 2 条分录：少于 2 条无法构成双腿，多于 2 条（拆分交易）
 * 预填简单模式会静默丢腿，同样返回 null 让 UI 走高级模式。
 */
export function parsePostingsToLegs(postings: Posting[]): TransactionLegs | null {
  if (postings.length !== 2) return null;
  const expensePosting = postings.find(p => p.account.startsWith('Expenses'));
  const incomePosting = postings.find(p => p.account.startsWith('Income'));
  const assetPosting = postings.find(p => isAssetLike(p.account));

  if (expensePosting) {
    return {
      direction: 'expense',
      sourceAccount: assetPosting?.account ?? '',
      targetAccount: expensePosting.account,
      amount: abs(expensePosting.amount) || abs(assetPosting?.amount),
      currency: expensePosting.currency ?? assetPosting?.currency ?? 'CNY',
    };
  }
  if (incomePosting) {
    return {
      direction: 'income',
      sourceAccount: assetPosting?.account ?? '',
      targetAccount: incomePosting.account,
      amount: abs(incomePosting.amount) || abs(assetPosting?.amount),
      currency: incomePosting.currency ?? assetPosting?.currency ?? 'CNY',
    };
  }
  // 转账：两条资金腿，带负号的一条为转出方；都不带负号则保持原顺序
  if (isAssetLike(postings[0].account) && isAssetLike(postings[1].account)) {
    const [first, second] = postings;
    const source = first.amount?.startsWith('-')
      ? first
      : second.amount?.startsWith('-')
        ? second
        : first;
    const target = source === first ? second : first;
    return {
      direction: 'transfer',
      sourceAccount: source.account,
      targetAccount: target.account,
      amount: abs(source.amount) || abs(target.amount),
      currency: source.currency ?? target.currency ?? 'CNY',
    };
  }
  return null;
}
