import { loadConfig, loadDotEnvFile } from './config.js';
import { buildApp } from './http.js';
import { AuthService } from './auth/authService.js';
import { TotpService } from './auth/totpService.js';
import { FileStore } from './storage/fileStore.js';
import { NodePtyAdapter } from './terminal/NodePtyAdapter.js';
import { TmuxPtyAdapter } from './terminal/TmuxPtyAdapter.js';
import { TerminalManager } from './terminal/TerminalManager.js';
import { fatalStartupExitCode, validateRuntimeState } from './runtimeState.js';
async function main() {
    const config = loadConfig(loadDotEnvFile());
    const store = new FileStore(config.statePath);
    await store.init({ createIfMissing: false });
    validateRuntimeState(config, await store.read());
    const totpService = new TotpService('NTerminal');
    const authService = new AuthService(config, store, { totpService });
    // Prefer the tmux-backed adapter when available so PTYs survive
    // `nterminalctl restart` and NTerminal updates without losing shell state.
    // Falls back to the raw node-pty adapter when tmux isn't installed; the
    // rest of the system works the same, just without across-restart
    // persistence. Set NTERMINAL_PTY_PERSIST=false to force the fallback.
    const tmuxAdapter = process.env.NTERMINAL_PTY_PERSIST === 'false' ? null : TmuxPtyAdapter.detect();
    const ptyAdapter = tmuxAdapter ?? new NodePtyAdapter();
    const terminalManager = new TerminalManager(config, ptyAdapter);
    await terminalManager.restoreSessions();
    const app = await buildApp(config, {
        authService,
        fileStore: store,
        terminalManager
    });
    app.log.info({ adapter: tmuxAdapter ? 'tmux' : 'node-pty' }, tmuxAdapter
        ? 'PTY persistence enabled — shells survive NTerminal restart'
        : 'PTY persistence disabled (tmux not detected or disabled); shells die on NTerminal restart');
    store.setErrorHandler((err) => app.log.error({ err }, 'fileStore coalesced flush failed'));
    const shutdown = async (signal) => {
        app.log.info({ signal }, 'shutting down');
        terminalManager.closeAll();
        await app.close();
        await store.flush();
        process.exit(0);
    };
    process.once('SIGINT', () => void shutdown('SIGINT'));
    process.once('SIGTERM', () => void shutdown('SIGTERM'));
    // Last-ditch safety net for any path that exits without going through shutdown
    // (uncaught lifecycle, beforeExit). Sync flush so it works during process tear-down.
    process.on('beforeExit', () => store.flushSync());
    await app.listen({ host: config.host, port: config.port });
}
main().catch((error) => {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`NTerminal fatal startup error: ${message}`);
    process.exit(fatalStartupExitCode);
});
//# sourceMappingURL=index.js.map