/**
 * 银行 CSV 适配器（plan.md「2.5 CSV 导入增强」）。
 * 补充招商银行、工商银行、通用银行适配器。
 *
 * 复用 statements.ts 的 parseCsv 模式，但各银行表头字段不同，
 * 需要独立的字段映射与方向解析。
 */

import { detectDirection } from '../core/constants';
import { negateDecimal } from '../core/decimal';
import type { ImportedEvent } from '../core/types';
import { splitCsvLine, pickFirst } from './csvUtils';
import { logger } from '../../utils/logger';

/** 通用 CSV 行解析（引号感知，支持含逗号字段）。 */
function parseCsvRows(content: string): Record<string, string>[] {
  const lines = content.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').split('\n').filter(l => l.trim());
  const headerLine = lines.find(l => /交易|金额|时间|日期|余额|商户|对方/i.test(l));
  if (!headerLine) {
    logger.error('adapters', '[CSV解析] 未找到包含交易/金额/日期的表头行');
    throw new Error('未找到账单表头');
  }
  const headers = splitCsvLine(headerLine).map(h => h.trim().replace(/^"|"$/g, ''));
  return lines.slice(lines.indexOf(headerLine) + 1).map(line => {
    const values = splitCsvLine(line).map(v => v.trim().replace(/^"|"$/g, ''));
    return Object.fromEntries(headers.map((h, i) => [h, values[i] ?? '']));
  }).filter(r => Object.values(r).some(Boolean));
}

/** 招商银行 CSV 适配器。 */
export function parseCmbCsv(content: string): ImportedEvent[] {
  const rows = parseCsvRows(content);
  return rows.map((row, i) => {
    let amount = pickFirst(row, ['交易金额', '金额', '发生额']).replace(/[¥￥\s]/g, '').replace(/,/g, '');
    const type = pickFirst(row, ['交易类型', '摘要', '收/支']);
    const direction = detectDirection(type + amount);
    if (direction === 'expense' && !amount.startsWith('-')) amount = negateDecimal(amount);
    const date = pickFirst(row, ['交易日期', '日期', '时间']).replace(/[/.]/g, '-').slice(0, 10);
    return {
      id: `CMB:${pickFirst(row, ['交易序号', '凭证号']) || i}`,
      occurredAt: date || new Date().toISOString().slice(0, 10),
      amount,
      currency: 'CNY',
      direction,
      counterparty: pickFirst(row, ['交易对方', '对方账户', '商户名称']),
      memo: pickFirst(row, ['摘要', '交易描述', '备注']),
      raw: row,
    };
  });
}

/** 工商银行 CSV 适配器。 */
export function parseIcbcCsv(content: string): ImportedEvent[] {
  const rows = parseCsvRows(content);
  return rows.map((row, i) => {
    let amount = pickFirst(row, ['交易金额', '金额', '发生额']).replace(/[¥￥\s]/g, '').replace(/,/g, '');
    const type = pickFirst(row, ['交易类型', '摘要']);
    const direction = detectDirection(type + amount);
    if (direction === 'expense' && !amount.startsWith('-')) amount = negateDecimal(amount);
    const date = pickFirst(row, ['交易时间', '交易日期', '日期']).replace(/[/.]/g, '-').slice(0, 10);
    return {
      id: `ICBC:${pickFirst(row, ['流水号', '交易序号']) || i}`,
      occurredAt: date || new Date().toISOString().slice(0, 10),
      amount,
      currency: 'CNY',
      direction,
      counterparty: pickFirst(row, ['对方户名', '对方账户', '交易对方']),
      memo: pickFirst(row, ['摘要', '交易描述', '备注']),
      raw: row,
    };
  });
}

/** 通用银行 CSV 适配器（未知银行格式）。 */
export function parseGenericBankCsv(content: string, source = 'bank'): ImportedEvent[] {
  const rows = parseCsvRows(content);
  return rows.map((row, i) => {
    let amount = pickFirst(row, ['金额', '交易金额', '发生额', 'Amount']).replace(/[¥￥\s]/g, '').replace(/,/g, '');
    const type = pickFirst(row, ['交易类型', '摘要', '收/支', 'Type']);
    const direction = detectDirection(type + amount);
    if (direction === 'expense' && !amount.startsWith('-')) amount = negateDecimal(amount);
    const date = pickFirst(row, ['交易日期', '日期', '时间', 'Date']).replace(/[/.]/g, '-').slice(0, 10);
    return {
      id: `${source}:${pickFirst(row, ['交易序号', '流水号', 'id']) || i}`,
      occurredAt: date || new Date().toISOString().slice(0, 10),
      amount,
      currency: pickFirst(row, ['币种', 'Currency']) || 'CNY',
      direction,
      counterparty: pickFirst(row, ['交易对方', '对方账户', '商户', 'Counterparty']),
      memo: pickFirst(row, ['摘要', '备注', '描述', 'Memo']),
      raw: row,
    };
  });
}
