#!/usr/bin/env node

/**
 * Xero MCP Server - Main Entry Point
 * Dual transport support (stdio/SSE) with graceful shutdown
 */

import { XeroClient } from './clients/xero.js';
import { XeroMCPServer } from './server.js';

async function main() {
  // Required environment variables
  const accessToken = process.env.XERO_ACCESS_TOKEN;
  const tenantId = process.env.XERO_TENANT_ID;

  if (!accessToken) {
    console.error('Error: XERO_ACCESS_TOKEN environment variable is required');
    process.exit(1);
  }

  if (!tenantId) {
    console.error('Error: XERO_TENANT_ID environment variable is required');
    process.exit(1);
  }

  // Optional configuration
  const config = {
    accessToken,
    tenantId,
    baseUrl: process.env.XERO_BASE_URL,
    timeout: process.env.XERO_TIMEOUT ? parseInt(process.env.XERO_TIMEOUT, 10) : undefined,
    retryAttempts: process.env.XERO_RETRY_ATTEMPTS
      ? parseInt(process.env.XERO_RETRY_ATTEMPTS, 10)
      : undefined,
    retryDelayMs: process.env.XERO_RETRY_DELAY_MS
      ? parseInt(process.env.XERO_RETRY_DELAY_MS, 10)
      : undefined
  };

  // Initialize Xero client
  const xeroClient = new XeroClient(config);

  // Initialize MCP server
  const mcpServer = new XeroMCPServer(xeroClient);

  // Graceful shutdown
  const shutdown = async () => {
    console.error('Shutting down Xero MCP server...');
    process.exit(0);
  };

  process.on('SIGINT', shutdown);
  process.on('SIGTERM', shutdown);

  // Start server
  await mcpServer.run();
}

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