import type { CardItem, JsonValue, WorkbenchItem } from "../types";
import type {
  ManualToolAsyncOptions,
  ManualToolDefinition,
  ManualToolJob,
  ManualToolResult,
} from "./api";

export type RuntimeSurface = "feed" | "workbench";
export type RuntimeItem = CardItem | WorkbenchItem;

export interface RuntimeHost {
  surface: RuntimeSurface;
  item: RuntimeItem;
  getState(): Record<string, JsonValue>;
  replaceState(nextState: Record<string, JsonValue>): Promise<Record<string, JsonValue>>;
  patchState(patch: Record<string, JsonValue>): Promise<Record<string, JsonValue>>;
  setLiveContent(snapshot: JsonValue | null | undefined): void;
  getLiveContent(): JsonValue | undefined;
  setSelection(selection: JsonValue | null | undefined): void;
  getSelection(): JsonValue | undefined;
  clearSelection(): void;
  setRefreshHandler(handler: (() => void) | null | undefined): void;
  runRefresh(): boolean;
  requestFeedRefresh(): void;
  callTool(toolName: string, argumentsValue?: Record<string, JsonValue>): Promise<ManualToolResult>;
  startToolCall(
    toolName: string,
    argumentsValue?: Record<string, JsonValue>,
  ): Promise<ManualToolJob>;
  getToolJob(jobId: string): Promise<ManualToolJob>;
  callToolAsync(
    toolName: string,
    argumentsValue?: Record<string, JsonValue>,
    options?: ManualToolAsyncOptions,
  ): Promise<ManualToolResult>;
  listTools(): Promise<ManualToolDefinition[]>;
  renderMarkdown(markdown: string, options?: { inline?: boolean }): string;
  copyText(text: string): Promise<void>;
  getThemeName(): string;
  getThemeValue(tokenName: string): string;
}

export interface RuntimeContext {
  root: HTMLElement;
  item: RuntimeItem;
  state: Record<string, JsonValue>;
  host: RuntimeHost;
}

export interface MountedRuntimeCard {
  update?(context: RuntimeContext): void;
  destroy?(): void;
}

export interface RuntimeModule {
  mount(context: RuntimeContext): MountedRuntimeCard | undefined;
}
