/**
 * Telex transport adapter — dry-run email-to-telex normalization for KTT rail.
 * Usage: node dist/cli.js [--dry-run] <raw-file>
 */
import { readFileSync } from 'fs';

function extractTelexFromEmail(payload: string): string {
  const text = payload.trim();
  if (text.startsWith('{') && text.includes('body')) {
    try {
      const obj = JSON.parse(text) as Record<string, unknown>;
      return String(obj.body ?? obj.text ?? text);
    } catch {
      /* continue */
    }
  }
  const parts = text.split(/\n\n/);
  if (parts.length >= 2 && /^From:/m.test(text)) return parts.slice(1).join('\n\n').trim();
  return text;
}

function parseFields(body: string): Record<string, string> {
  const fields: Record<string, string> = {};
  for (const line of body.split('\n')) {
    const upper = line.toUpperCase();
    if (upper.startsWith('ORDERING:')) fields.debtorId = line.split(':').slice(1).join(':').trim();
    if (upper.startsWith('BENEFICIARY:')) fields.creditorId = line.split(':').slice(1).join(':').trim();
    if (upper.startsWith('AMOUNT:')) {
      const p = line.split(':').slice(1).join(':').trim().split(/\s+/);
      if (p.length >= 2) {
        fields.currencyCode = p[0];
        fields.amount = p[1];
      }
    }
  }
  return fields;
}

const dryRun = process.argv.includes('--dry-run') || process.env.TELEX_TRANSPORT_DRY_RUN === '1';
const file = process.argv.find((a) => !a.startsWith('-') && a !== process.argv[0] && a !== process.argv[1]);
const raw = file ? readFileSync(file, 'utf8') : readFileSync(0, 'utf8');
const normalizedBody = extractTelexFromEmail(raw);
const messageType = normalizedBody.includes(':20:') ? 'TELEX_KTT' : 'KTT';

console.log(
  JSON.stringify({
    dryRun,
    format: 'ktt',
    messageType,
    normalizedBody,
    normalizedFields: parseFields(normalizedBody),
  })
);
