import React from 'react';
import { render } from 'ink';
import { App } from './components/index.js';
import type { ManagedSession } from '../../session/index.js';
import type { ModelClient } from '../../models/types.js';
import type { ModelRouter } from '../../models/router.js';
import type { NativeAgent } from '../../backends/native/agent.js';
import type { HookEngine } from '../../hooks/index.js';
import type { ModelConfig, ModelProvider } from '../../config/index.js';

export interface FullscreenTuiConfig {
  session: ManagedSession;
  modelClient: ModelClient;
  modelRouter?: ModelRouter;
  systemPrompt: string;
  model: string;
  agent?: NativeAgent;
  hookEngine?: HookEngine;
  modelProviderConfigs?: Partial<Record<ModelProvider, ModelConfig>>;
  onExit?: () => void;
}

export async function startFullscreenTui(config: FullscreenTuiConfig): Promise<void> {
  // Ensure stdin is in a clean state for Ink
  if (process.stdin.isPaused()) {
    process.stdin.resume();
  }

  if (config.agent && config.modelRouter) {
    config.agent.setModelTier(config.modelRouter.getTier());
  }

  const { waitUntilExit } = render(
    React.createElement(App, {
      session: config.session,
      modelClient: config.modelClient,
      modelRouter: config.modelRouter,
      systemPrompt: config.systemPrompt,
      model: config.model,
      agent: config.agent,
      hookEngine: config.hookEngine,
      modelProviderConfigs: config.modelProviderConfigs,
      onExit: config.onExit,
    }),
  );

  await waitUntilExit();
}
