import type { Terminal } from 'xterm';
import type { FitAddon } from 'xterm-addon-fit';
import type { IProcessHandle } from '../../00group-runtime/index.js';

/**
 * Type of terminal tab based on its source/purpose
 */
export type TTerminalTabType =
  | 'shell'           // Default interactive shell (jsh)
  | 'script'          // Script from package.json
  | 'package-update'  // Package update process
  | 'custom';         // External process from API

/**
 * Represents a single terminal tab instance
 */
export interface ITerminalTab {
  /** Unique identifier for the tab */
  id: string;

  /** Display label for the tab */
  label: string;

  /** Icon name (lucide icon) */
  iconName: string;

  /** Type of terminal process */
  type: TTerminalTabType;

  /** Whether the tab can be closed */
  closeable: boolean;

  /** xterm.js Terminal instance */
  terminal: Terminal;

  /** FitAddon for this terminal */
  fitAddon: FitAddon;

  /** Process handle (if process is running) */
  process: IProcessHandle | null;

  /** Process input writer (for interactive terminals) */
  inputWriter: WritableStreamDefaultWriter<string> | null;

  /** Whether the process has exited */
  exited: boolean;

  /** Exit code (if process has exited) */
  exitCode: number | null;

  /** Timestamp when tab was created */
  createdAt: number;

  /** Optional metadata for script tabs */
  metadata?: {
    scriptName?: string;
    packageName?: string;
    command?: string;
  };
}

/**
 * Options for creating a new terminal tab
 */
export interface ICreateTerminalTabOptions {
  /** Display label (auto-generated if not provided) */
  label?: string;

  /** Tab type */
  type: TTerminalTabType;

  /** Icon name override */
  iconName?: string;

  /** Whether the tab can be closed (default: true for non-shell) */
  closeable?: boolean;

  /** Command to spawn (default: 'jsh' for shell type) */
  command?: string;

  /** Command arguments */
  args?: string[];

  /** Additional metadata */
  metadata?: ITerminalTab['metadata'];

  /** Whether to switch to this tab after creation (default: true) */
  switchToTab?: boolean;
}

/**
 * Event detail for terminal tab events
 */
export interface ITerminalTabEventDetail {
  tabId: string;
}

/**
 * Event detail for tab switch events
 */
export interface ITerminalTabSwitchEventDetail {
  tabId: string;
  previousTabId: string | null;
}

/**
 * Event detail for process completion
 */
export interface ITerminalProcessCompleteEventDetail {
  tabId: string;
  exitCode: number;
}

/**
 * Event detail for run-process events from bottom bar
 */
export interface IRunProcessEventDetail {
  type: TTerminalTabType;
  label: string;
  command: string;
  args?: string[];
  metadata?: {
    scriptName?: string;
    packageName?: string;
  };
}
