#!/usr/bin/env node

/**
 * CCIP Relay Service
 * Monitors MessageSent events on Chain 138 and relays messages to Ethereum Mainnet
 */

import { ethers } from 'ethers';
import dotenv from 'dotenv';
import winston from 'winston';
import { RelayService } from './src/RelayService.js';
import { config } from './src/config.js';
import { startRelayHealthServer } from './src/healthServer.js';

// Env is loaded in config.js before use
dotenv.config();

// Configure logger
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.splat(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    }),
    new winston.transports.File({ filename: 'relay-error.log', level: 'error' }),
    new winston.transports.File({ filename: 'relay-combined.log' })
  ]
});

async function main() {
  logger.info('Starting CCIP Relay Service...');
  logger.info('Configuration:', {
    sourceChain: config.sourceChain.name,
    sourceChainId: config.sourceChain.chainId,
    destinationChain: config.destinationChain.name,
    destinationChainId: config.destinationChain.chainId
  });

  try {
    const relayService = new RelayService(config, logger);
    let healthServer = null;
    
    // Start monitoring
    await relayService.start();
    healthServer = await startRelayHealthServer(relayService, logger);
    
    logger.info('Relay service started successfully');
    
    // Handle graceful shutdown
    process.on('SIGINT', async () => {
      logger.info('Received SIGINT, shutting down gracefully...');
      if (healthServer) {
        healthServer.close();
      }
      await relayService.stop();
      process.exit(0);
    });
    
    process.on('SIGTERM', async () => {
      logger.info('Received SIGTERM, shutting down gracefully...');
      if (healthServer) {
        healthServer.close();
      }
      await relayService.stop();
      process.exit(0);
    });
    
  } catch (error) {
    logger.error('Failed to start relay service:', error);
    process.exit(1);
  }
}

main().catch((error) => {
  logger.error('Unhandled error:', error);
  process.exit(1);
});
