#!/usr/bin/env node

process.noDeprecation = true;

const fs = require('fs');
const path = require('path');

// Before loading dist (logger reads NODE_ENV at import time): default env for
// published npm installs vs local / linked checkouts — see resolveDefaultNodeEnv.
if (!process.env.NODE_ENV) {
  try {
    const {
      resolveDefaultNodeEnv,
    } = require('../dist/cli/resolveDefaultNodeEnv.js');
    const pkgRoot = path.resolve(__dirname, '..');
    const pkg = JSON.parse(
      fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8'),
    );
    process.env.NODE_ENV = resolveDefaultNodeEnv(pkgRoot, pkg.name);
  } catch {
    process.env.NODE_ENV = 'development';
  }
}

// In MCP mode, stdout is reserved for the JSON-RPC protocol stream. The dist
// logger's redirectLogsToStderr() runs inside startMCPServer, but module-level
// log calls fire at import time — before that hook. Patch console output here
// so those early lines (and any future ones) go to stderr instead of corrupting
// the protocol stream.
if (process.argv.includes('mcp')) {
  console.log = console.error.bind(console);
  console.info = console.error.bind(console);
  console.warn = console.error.bind(console);
}

// Import the compiled main function
const { main } = require('../dist/index.js');

// Handle uncaught exceptions gracefully
process.on('uncaughtException', (error) => {
  console.error('Uncaught exception:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection at:', promise, 'reason:', reason);
  process.exit(1);
});

// Handle Ctrl+C gracefully
process.on('SIGINT', () => {
  console.log('\n👋 Goodbye!');
  process.exit(0);
});

// Start the CLI
main().catch((error) => {
  console.error('CLI error:', error);
  process.exit(1);
});
