#!/usr/bin/env node
import { resolve } from 'path';
import { mkdirSync } from 'fs';
import { createSwiftListener } from './listener';
import { loadListenerConfig } from './resourceRegistry';

function parseArgs(argv: string[]) {
  let once = false;
  let projectRoot = process.env.PROXMOX_ROOT ?? process.cwd();
  for (let i = 2; i < argv.length; i++) {
    const a = argv[i];
    if (a === '--once') once = true;
    else if (a === '--project-root') projectRoot = argv[++i] ?? projectRoot;
    else if (a.startsWith('--project-root=')) projectRoot = a.slice('--project-root='.length);
    else if (a === '--help' || a === '-h') {
      console.log(`Usage: swift-listener [--once] [--project-root PATH]

Inbound adapters (env flags):
  SWIFT_LISTENER_FILE_INBOX=1|0     file drop inbox (default on)
  SWIFT_LISTENER_WEBHOOK=1          HTTP POST /swift/inbound + GET /health
  SWIFT_LISTENER_P2P_RAIL=1         banktransfer Financial Broadcast poll
  SWIFT_LISTENER_FIN_GATEWAY=1      FIN / Alliance Access HTTP poll
  SWIFT_LISTENER_FIN_TCP=1          SWIFT FIN copy TCP listener
  SWIFT_LISTENER_AS4_INBOX=1        AS4 / ISO drop directory poll
  SWIFT_LISTENER_MAIL_INBOX=1       mail attachment drop directory poll

Outbound (on match):
  SWIFT_LISTENER_OMNL_FORWARD=1     local ISO store + token-aggregation API
  SWIFT_LISTENER_INTAKE_GATEWAY=1   ISO20022IntakeGateway (dry-run unless EXECUTE=1)
  SWIFT_LISTENER_GATEWAY_EXECUTE=1  broadcast submitInbound tx

Credentials:
  P2P_BASE_URL / P2P_BEARER_TOKEN / P2P_API_KEY
  FIN_GATEWAY_URL / ALLIANCE_ACCESS_URL / FIN_GATEWAY_TOKEN
  SWIFT_FIN_TCP_PORT (default 5001)
  SWIFT_LISTENER_WEBHOOK_TOKEN
  RPC_URL_138 / PRIVATE_KEY / ISO20022_INTAKE_GATEWAY_MAINNET
  TOKEN_AGGREGATION_URL / OMNL_API_KEY
`);
      process.exit(0);
    }
  }
  return { once, projectRoot: resolve(projectRoot) };
}

async function main() {
  const { once, projectRoot } = parseArgs(process.argv);
  const config = loadListenerConfig(projectRoot);

  const dirs = [
    config.storage.inboxDir,
    config.storage.eventsDir,
    config.storage.as4InboxDir,
    config.storage.mailInboxDir,
  ].filter(Boolean) as string[];

  for (const d of dirs) {
    mkdirSync(resolve(projectRoot, d), { recursive: true });
  }

  const listener = createSwiftListener(projectRoot);
  await listener.run({ once });
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
