/**
 * 无障碍文本解析器（微信/支付宝账单详情页的文本解析）。
 *
 * 从 automationPipeline.ts 提取，职责：
 * - 解析微信/支付宝无障碍文本为 ImportedEvent
 * - 纯文本匹配逻辑，不依赖 RN/Expo 原生模块
 */

import { compareDecimals } from '../domain/decimal';
import type { ImportedEvent } from '../domain/types';
import { logger } from '../utils/logger';

/**
 * 解析微信账单详情无障碍文本。
 * 特征：包含 "交易单号" 或 "退款单号" 或 "本服务由财付通提供"
 */
function parseWechatTexts(texts: string[], packageName: string): ImportedEvent | null {
  if (!texts.includes('交易单号') && !texts.includes('退款单号') && !texts.includes('本服务由财付通提供')) {
    return null;
  }

  let amountStr = '0';
  let merchant = '';
  let time = '';
  let direction: 'expense' | 'income' = 'expense';
  const amountPattern = /^([+-])?(\d+(\.\d{1,2})?)$/;

  for (const text of texts) {
    const match = text.match(amountPattern);
    if (match) {
      amountStr = match[2];
      if (match[1] === '+') direction = 'income';
      break;
    }
  }

  const amtIndex = texts.findIndex(t => amountPattern.test(t));
  if (amtIndex > 0) {
    merchant = texts[amtIndex - 1];
  } else {
    merchant = texts[0] || '';
  }
  merchant = merchant.split(',')[0].replace(/-退款$/, '');

  const timeLabelIndex = texts.findIndex(t => t.includes('时间'));
  if (timeLabelIndex !== -1 && timeLabelIndex + 1 < texts.length) {
    time = texts[timeLabelIndex + 1];
  } else {
    time = new Date().toISOString().replace('T', ' ').substring(0, 19);
  }

  if (compareDecimals(amountStr, '0') > 0 && merchant) {
    return {
      id: 'nodes_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9),
      occurredAt: time,
      amount: amountStr,
      currency: 'CNY',
      direction,
      counterparty: merchant,
      memo: texts.includes('已退款') ? '退款' : '微信支付',
      raw: { packageName },
    };
  }
  return null;
}

/**
 * 解析支付宝账单详情无障碍文本。
 * 特征：包含 "创建时间" 或 "账单详情" 或 "对此订单有疑问"
 */
function parseAlipayTexts(texts: string[], packageName: string): ImportedEvent | null {
  const isDetailPage = texts.includes('创建时间') || texts.includes('账单详情') || texts.includes('对此订单有疑问');
  if (!isDetailPage) {
    logger.debug('layout', `[无障碍] 支付宝文本解析跳过：未识别为账单详情页特征`);
    return null;
  }

  let amountStr = '0';
  let merchant = '';
  let time = '';
  let direction: 'expense' | 'income' = 'expense';
  let memo = '支付宝账单';

  for (const text of texts) {
    const trimmed = text.trim();
    // 匹配 "支出12.93元" / "收入50.00元" / "-12.93元" / "12.93元" / "12.93"
    const match = trimmed.match(/^(?:(支出|收入|[+-]))?\s*(\d+(\.\d+)?)元?$/);
    if (match && match[2]) {
      const val = match[2];
      // 避免匹配整年或订单纯数字（如 "2026"），必须带小数点或包含支出/收入/元标志
      if (val.includes('.') || trimmed.endsWith('元') || trimmed.startsWith('支出') || trimmed.startsWith('收入') || trimmed.startsWith('-') || trimmed.startsWith('+')) {
        amountStr = val;
        const prefix = match[1];
        if (prefix === '+' || prefix === '收入') {
          direction = 'income';
        } else if (prefix === '-' || prefix === '支出') {
          direction = 'expense';
        } else if (texts.some(t => t.includes('收款') || t.includes('收入') || t.includes('收益') || t.includes('收到') || t.includes('红包'))) {
          direction = 'income';
        }
        break;
      }
    }
  }

  const amtIndex = texts.findIndex(t => /^(?:(支出|收入|[+-]))?\s*\d+(\.\d+)?元?$/.test(t.trim()));
  if (amtIndex > 0) {
    merchant = texts[amtIndex - 1];
  } else {
    merchant = texts[0] || '';
  }

  const timeLabelIndex = texts.indexOf('创建时间');
  if (timeLabelIndex !== -1 && timeLabelIndex + 1 < texts.length) {
    time = texts[timeLabelIndex + 1];
  } else {
    time = new Date().toISOString().replace('T', ' ').substring(0, 19);
  }

  const memoLabelIndex = texts.indexOf('商品说明');
  if (memoLabelIndex !== -1 && memoLabelIndex + 1 < texts.length) {
    memo = texts[memoLabelIndex + 1];
  }

  const catLabelIndex = texts.indexOf('账单分类');
  if (catLabelIndex !== -1 && catLabelIndex + 1 < texts.length) {
    const rawCat = texts[catLabelIndex + 1];
    if (rawCat.includes('理财') || rawCat.includes('收益') || memo.includes('收益发放') || rawCat.includes('红包')) {
      direction = 'income';
    }
  }

  if (compareDecimals(amountStr, '0') > 0 && merchant) {
    return {
      id: 'nodes_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9),
      occurredAt: time,
      amount: amountStr,
      currency: 'CNY',
      direction,
      counterparty: merchant,
      memo,
      raw: { packageName },
    };
  }

  logger.info('layout', `[无障碍] 支付宝详情页解析未成功原因: 金额解析无效(amountStr="${amountStr}") 或 商户为空(merchant="${merchant}") | 截获完整文本: ${JSON.stringify(texts)}`);
  return null;
}

/**
 * 直接通过无障碍文本进行解析（无需截图 OCR，速度更快且省电）。
 * @returns 解析出的 ImportedEvent，未识别返回 null
 */
export function parseAccessibilityTexts(texts: string[], packageName: string): ImportedEvent | null {
  if (packageName === 'com.tencent.mm') {
    return parseWechatTexts(texts, packageName);
  }
  if (packageName === 'com.eg.android.AlipayGphone') {
    return parseAlipayTexts(texts, packageName);
  }
  return null;
}
