import type {
  AgentState,
  CardItem,
  CardMessageMetadata,
  ClientMessage,
  LogLine,
  ServerMessage,
  SessionHistoryLine,
  SessionSummary,
  WorkbenchItem,
} from "../../types";

export interface WebRTCState {
  connected: boolean;
  connecting: boolean;
  textOnly: boolean;
  agentState: AgentState;
  logLines: LogLine[];
  cards: CardItem[];
  workbenchItems: WorkbenchItem[];
  sessions: SessionSummary[];
  activeSessionId: string;
  activeSession: SessionSummary | null;
  sessionLoading: boolean;
  textStreaming: boolean;
  voiceStatus: string;
  statusVisible: boolean;
  remoteAudioEl: HTMLAudioElement | null;
  remoteStream: MediaStream | null;
  sendJson(msg: ClientMessage): void;
  sendTextMessage(text: string, metadata?: CardMessageMetadata): Promise<void>;
  dismissCard(id: number): void;
  dismissWorkbenchItem(id: string): Promise<void>;
  promoteWorkbenchItem(id: string): Promise<void>;
  setTextOnly(enabled: boolean): void;
  switchSession(chatId: string): Promise<void>;
  createSession(title?: string): Promise<void>;
  renameSession(chatId: string, title: string): Promise<void>;
  deleteSession(chatId: string): Promise<void>;
  connect(): Promise<void>;
}

export type AppendLine = (
  role: string,
  text: string,
  timestamp: string,
  contextLabel?: string,
) => void;
export type UpsertCard = (item: Omit<CardItem, "id">) => void;
export type SetAgentState = (updater: (prev: AgentState) => AgentState) => void;
export type RawPersistedCard =
  | Extract<ServerMessage, { type: "card" }>
  | (Omit<Extract<ServerMessage, { type: "card" }>, "type"> & { type?: "card" });
export type RawWorkbenchItem =
  | Extract<ServerMessage, { type: "workbench" }>
  | (Omit<Extract<ServerMessage, { type: "workbench" }>, "type"> & {
      type?: "workbench";
    });

export interface IdleFallbackControls {
  clear(): void;
  schedule(delayMs?: number): void;
}

export interface RTCRefs {
  pcRef: { current: RTCPeerConnection | null };
  dcRef: { current: RTCDataChannel | null };
  remoteAudioRef: { current: HTMLAudioElement | null };
  micSendersRef: { current: RTCRtpSender[] };
  localTracksRef: { current: MediaStreamTrack[] };
}

export interface RTCCallbacks {
  setConnected: (v: boolean) => void;
  setConnecting: (v: boolean) => void;
  setRemoteStream: (s: MediaStream | null) => void;
  showStatus: (text: string, persistMs?: number) => void;
  appendLine: AppendLine;
  onDcMessage: (raw: string) => void;
  onDcOpen: () => void;
  closePC: () => void;
}

export interface SessionDetailResponse {
  session: SessionSummary;
  messages: SessionHistoryLine[];
}
