import type { ErrorLogItem } from '../errorLogApi';

export type ChatComposerAttachment = {
  id: string;
  name: string;
  path: string;
  publicUrl: string;
  size: number;
  mimeType: string;
};

export type ChatStructuredPreview = {
  type: 'image' | 'markdown' | 'html' | 'resource' | 'editable';
  url?: string | null;
  content?: string | null;
  alt?: string | null;
  title?: string | null;
  editable?: boolean | null;
};

export type ChatPromptContextRef = {
  key: 'prompt_parent_question';
  promptTitle: string;
  promptDescription?: string | null;
  parentQuestionText?: string | null;
};

export type ChatMessagePart =
  | {
      type: 'link_card';
      title: string;
      url: string;
      actionLabel?: string | null;
    }
  | {
      type: 'preview_card';
      title: string;
      description?: string | null;
      kindLabel?: string | null;
      actionLabel?: string | null;
      preview: ChatStructuredPreview;
    }
  | {
      type: 'prompt';
      title: string;
      description?: string | null;
      submitLabel?: string | null;
      mode?: 'queue' | 'direct' | null;
      multiple?: boolean;
      responseTemplate?: string | null;
      freeTextLabel?: string | null;
      freeTextPlaceholder?: string | null;
      currentStepKey?: string | null;
      steps?: Array<{
        key: string;
        title: string;
        description?: string | null;
        submitLabel?: string | null;
        mode?: 'queue' | 'direct' | null;
        multiple?: boolean;
        optional?: boolean;
        responseTemplate?: string | null;
        freeTextLabel?: string | null;
        freeTextPlaceholder?: string | null;
        selectedValues?: string[];
        options: Array<{
          value: string;
          label: string;
          description?: string | null;
          preview?: ChatStructuredPreview | null;
        }>;
      }>;
      readOnly?: boolean;
      selectedValues?: string[];
      resolvedBy?: 'user' | 'timeout' | 'system' | null;
      resolvedAt?: string | null;
      resultText?: string | null;
      attachments?: ChatComposerAttachment[];
      options: Array<{
        value: string;
        label: string;
        description?: string | null;
        preview?: ChatStructuredPreview | null;
      }>;
    };

export type ChatMessage = {
  id: number;
  author: 'codex' | 'system' | 'user';
  text: string;
  timestamp: string;
  clientRequestId?: string | null;
  deliveryStatus?: 'retrying' | 'failed' | null;
  retryCount?: number;
  parts?: ChatMessagePart[];
};

export type ChatCodexParticipant = {
  id: string;
  name: string;
  model: string;
  prompt?: string;
  chatTypeId?: string | null;
  defaultContextIds?: string[];
  role?: 'default' | 'moderator' | 'conversation' | 'reviewer';
};

export type ChatViewContext = {
  pageId: string;
  pageTitle: string;
  topMenu: string;
  focusedComponentId: string | null;
  pageUrl: string;
  appOrigin?: string;
  appDomain?: string;
  isStandaloneMode: boolean;
  pageVisibilityState: 'visible' | 'hidden';
  pageFocusState?: 'focused' | 'blurred';
  codexModel?: string | null;
  codexParticipants?: ChatCodexParticipant[];
  chatTypeId: string | null;
  chatTypeLabel: string;
  chatTypeDescription: string;
  chatTypeBaseDescription?: string;
  defaultContextIds?: string[];
  defaultContexts?: Array<{
    id: string;
    title: string;
    content: string;
  }>;
  customContextTitle?: string | null;
  customContextContent?: string | null;
};

export type ChatConversationSummary = {
  sessionId: string;
  clientId: string | null;
  isDraftOnly?: boolean;
  draftText: string;
  title: string;
  requestBadgeLabel?: string | null;
  codexModel?: string | null;
  chatTypeId: string | null;
  lastChatTypeId: string | null;
  generalSectionName: string | null;
  contextLabel: string | null;
  contextDescription: string | null;
  roomScope: Record<string, unknown> | null;
  notifyOffline: boolean;
  hasUnreadResponse: boolean;
  hasPendingAttention: boolean;
  currentRequestId: string | null;
  currentJobStatus: ChatJobStatus | null;
  currentJobMessage: string | null;
  currentQueueSize: number;
  currentStatusUpdatedAt: string | null;
  isPendingWork: boolean;
  pendingWorkReason: 'prompt' | 'analysis' | 'design' | null;
  lastRequestPreview: string;
  lastMessagePreview: string;
  lastResponsePreview: string;
  createdAt: string;
  updatedAt: string;
  lastMessageAt: string | null;
};

export type ChatShareRoomLinkContext = {
  kind: 'linked-session';
  sourceSessionId: string;
  sourceRequestId: string;
  sourceTitle: string | null;
  sourceRequestPreview: string | null;
  sourceChatTypeLabel: string | null;
  linkedAt: string | null;
};

export type ChatConversationRequestStatus =
  | 'accepted'
  | 'queued'
  | 'started'
  | 'completed'
  | 'failed'
  | 'cancelled'
  | 'removed';

export type ChatConversationRequestUsageSnapshot = {
  tokenTotals: {
    total: number;
    input: number;
    output: number;
    cached: number;
    reasoning: number;
  };
  totalTokens: number;
};

export type ChatConversationRequest = {
  sessionId: string;
  requestId: string;
  requesterClientId?: string | null;
  chatTypeId?: string | null;
  chatTypeLabel?: string;
  requestOrigin?: 'composer' | 'prompt' | null;
  parentRequestId?: string | null;
  promptContextRef?: ChatPromptContextRef | null;
  status: ChatConversationRequestStatus;
  statusMessage: string | null;
  retryCount?: number;
  userMessageId: number | null;
  userText: string;
  responseMessageId: number | null;
  responseText: string;
  usageSnapshot?: ChatConversationRequestUsageSnapshot | null;
  totalTokens?: number | null;
  hasResponse: boolean;
  canDelete: boolean;
  manualPromptCompletedAt?: string | null;
  manualVerificationCompletedAt?: string | null;
  createdAt: string;
  updatedAt: string;
  answeredAt: string | null;
  terminalAt: string | null;
};

export type ChatConversationActivityLog = {
  sessionId: string;
  requestId: string;
  lines: string[];
  updatedAt: string | null;
};

export type ChatSourceChangeSnapshot = {
  id: string;
  sessionId: string;
  clientId: string | null;
  conversationTitle: string;
  chatTypeId: string | null;
  chatTypeLabel: string;
  requestId: string;
  requestTitle: string;
  questionText: string;
  answerText: string;
  status: ChatConversationRequestStatus;
  sourceChangedAt: string;
  updatedAt: string;
  featureTags: string[];
  changedFiles: string[];
  currentSourceFiles: string[];
  diffBlocks: string[];
  hasSourceChanges: boolean;
  reviewStatus: 'reviewed' | 'not-reviewed';
  sourceChangeKind: 'request' | 'verification-group';
  sourceEntryIds: string[];
  conversationDeletedAt: string | null;
};

export type ChatActivityEvent = {
  requestId: string;
  line: string;
  lineCount: number;
  lineNo?: number;
};

export type ChatPanelView = 'chat' | 'runtime' | 'errors';

export type ChatJobMode = 'queue' | 'direct';
export type ChatJobStatus = 'queued' | 'started' | 'completed' | 'failed';

export type ChatRuntimeJobStatus = 'queued' | 'running';

export type ChatJobEvent = {
  requestId: string;
  status: ChatJobStatus;
  mode: ChatJobMode;
  queueSize: number;
  message: string;
};

export type ChatRuntimeJobItem = {
  requestId: string;
  sessionId: string;
  mode: ChatJobMode;
  status: ChatRuntimeJobStatus;
  summary: string;
  enqueuedAt: string;
  startedAt: string | null;
  pid: number | null;
};

export type ChatRuntimeSessionSummary = {
  sessionId: string;
  runningCount: number;
  queuedCount: number;
  latestRequestId: string | null;
  latestStatus: ChatRuntimeJobStatus | null;
};

export type ChatRuntimeSnapshot = {
  generatedAt: string;
  runningCount: number;
  queuedCount: number;
  sessionCount: number;
  running: ChatRuntimeJobItem[];
  queued: ChatRuntimeJobItem[];
  sessions: ChatRuntimeSessionSummary[];
  recent: Array<ChatRuntimeJobItem & { terminalStatus: ChatRuntimeTerminalStatus; lastUpdatedAt: string }>;
};

export type ChatRuntimeTerminalStatus = 'completed' | 'failed' | 'cancelled' | 'removed';

export type ChatRuntimeJobDetail = {
  item: ChatRuntimeJobItem | null;
  logs: string[];
  lastUpdatedAt: string | null;
  terminalStatus: ChatRuntimeTerminalStatus | null;
  availableActions: {
    cancel: boolean;
    remove: boolean;
  };
};

export type ErrorReferenceResource = {
  url: string;
  label: string;
  kind: 'image' | 'link' | 'preview';
  sourcePath: string;
  sourcePreview: string;
};

export type ErrorReferenceSummary = {
  resources: ErrorReferenceResource[];
  previewCount: number;
  imageCount: number;
  linkCount: number;
};

export type MainChatPanelProps = {
  initialView?: 'live' | 'errors';
  lockOuterScrollOnMobile?: boolean;
  panelVariant?: 'codex-live' | 'system-chat';
  mode?: 'live' | 'rooms';
  roomsPresentation?: 'default' | 'shared';
  roomsEntryMode?: 'list' | 'direct';
  sharedComposerActionVariant?: 'text' | 'icon';
  sharedComposerInputMode?: 'autosize' | 'fixed-scroll';
  onRoomsMinimize?: (() => void) | null;
  onRoomsClose?: (() => void) | null;
};

export type ChatServerEvent =
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:init';
      payload: {
        messages: ChatMessage[];
      };
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:message';
      payload: ChatMessage;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:message:update';
      payload: ChatMessage;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:status';
      payload: {
        connectedAt: string;
      };
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:error';
      payload: {
        message: string;
      };
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:job';
      payload: ChatJobEvent;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:runtime';
      payload: ChatRuntimeSnapshot;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:runtime:detail';
      payload: ChatRuntimeJobDetail;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:activity';
      payload: ChatActivityEvent;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'chat:request:update';
      payload: ChatConversationRequest;
    }
  | {
      eventId: number;
      sessionId: string;
      type: 'notification:messages-updated';
      payload:
        | {
            action: 'created' | 'updated';
            itemId: number;
            category: string;
            read: boolean;
          }
        | {
            action: 'deleted';
            itemId: number;
          };
    };

export type ChatConversationDetailResponse = {
  ok: boolean;
  item: ChatConversationSummary;
  messages: ChatMessage[];
  requests: ChatConversationRequest[];
  activityLogs: ChatConversationActivityLog[];
  oldestLoadedMessageId: number | null;
  hasOlderMessages: boolean;
};

export type ChatSourceChangeSnapshotListResponse = {
  ok: boolean;
  items: ChatSourceChangeSnapshot[];
};

export type ErrorLogViewerState = {
  errorLogs: ErrorLogItem[];
  selectedErrorLogId: number | null;
  isLoadingErrorLogs: boolean;
  errorLogLoadError: string;
  activeErrorResourceUrl: string;
  isErrorDetailExpanded: boolean;
};
