import './instrument.js';
import * as Sentry from '@sentry/node';
import React from 'react';
import { render } from 'ink';
import { App } from './App.js';

// Alternate screen buffer + clear + hide cursor
process.stdout.write('\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l');

const cleanup = () => {
  process.stdout.write('\x1b[?25h\x1b[?1049l');
};

process.on('exit', cleanup);
process.on('SIGINT', () => {
  cleanup();
  process.exit(0);
});
process.on('SIGTERM', () => {
  cleanup();
  process.exit(0);
});

process.on('uncaughtException', async (err) => {
  Sentry.captureException(err);
  await Sentry.flush(2000);
  cleanup();
  process.exit(1);
});

process.on('unhandledRejection', (reason) => {
  Sentry.captureException(reason);
});

const { waitUntilExit } = render(<App />);

waitUntilExit()
  .then(async () => {
    await Sentry.close(2000);
    cleanup();
  })
  .catch(async (err) => {
    Sentry.captureException(err);
    await Sentry.close(2000);
    cleanup();
  });
