// Types for the StationMonster SDK (index.mjs). Docs: https://stationmonster.com/developers/sdk

export declare const VERSION: string;
export declare const DEFAULT_BASE_URL: string;

export interface ClientOptions {
  /** An API key (sm_live_…) from Organization › API keys. Defaults to the STATIONMONSTER_API_KEY environment variable. */
  apiKey?: string;
  /** Or an OAuth access token (sm_oat_…) from signing in. */
  accessToken?: string;
  baseUrl?: string;
  /** Retries for rate limits (429) and temporary errors (5xx). Default 3. */
  maxRetries?: number;
  /** Per request, in milliseconds. Default 30000. */
  timeoutMs?: number;
  fetch?: typeof fetch;
}

export declare class StationMonsterError extends Error {
  status: number;
  body: { error?: string; required_scope?: string; [k: string]: unknown } | null;
  /** The permission the request needed, when that was the problem (403). */
  requiredScope: string | null;
  /** Seconds to wait (429). */
  retryAfter: number | null;
}

export type Row = Record<string, unknown>;
export interface Page<T = Row> {
  data: T[];
  has_more: boolean;
  next_cursor: string | null;
  total?: number;
}
/** {"column": "op.value"}: eq, neq, gt, gte, lt, lte, like, ilike (* = wildcard), in.(a,b), nin.(a,b), is.null, is.not_null, cs, cd, ov. */
export type Filters = Record<string, string | number | boolean | null | string[]>;
export interface DryRun {
  /** Test mode: everything runs and is checked, then undone. */
  dryRun?: boolean;
}

export interface Station {
  id: string;
  name: string;
  call_sign: string | null;
  frequency: string | null;
  format: string | null;
  market: string | null;
  timezone: string;
  created_at: string;
}

export interface NowPlaying {
  title: string | null;
  artist: string | null;
  type: string | null;
  media_id: string | null;
  text: string | null;
  started_at: string | null;
  mode: "auto" | "assist" | null;
  playout_running: boolean;
  updated_at: string | null;
}

export interface Player {
  /** 1–3 */
  player: number;
  status: "empty" | "loaded" | "playing" | "paused";
  logItemId: string | null;
  title: string | null;
  artist: string | null;
  itemType: string | null;
  positionMs: number;
  durationMs: number;
}

export interface Playout {
  engine: "cloud" | "browser";
  running: boolean;
  mode: "auto" | "assist" | null;
  players: Player[];
  now_playing: { title: string; artist: string | null; started_at: string } | null;
  /** Fader levels on air, 0–1 (cloud engine; null in the browser engine). */
  levels: Partial<Record<Fader, number>> | null;
  /** The now-playing text sent to streams, and your own override (set_now_playing_text) if any. */
  now_playing_text: { text: string | null; override: string | null } | null;
  /** The studio holding on-air control (null = none). yours = held by the key's person. */
  control: { studio: string; studio_id: string; taken_at: string; yours: boolean } | null;
  /** Studios whose mic may go to air as co-hosts, and studios asking to join. */
  cohosts: { studio: string; studio_id: string }[];
  cohost_requests: { studio: string; studio_id: string; asked_at: string }[];
  /** Mute audio is on in talkback headphones (never air). */
  muted: { since: string; by: string } | null;
  /** The key's person may run the air now (around their shift, or with On-air control any time). */
  can_operate: boolean;
  /** They may take over from the studio in control. */
  can_take_over: boolean;
}

export type PlayoutCommandName = "play_next" | "play_player" | "stop_player" | "pause_player" | "recue_player" | "stop_all" | "set_mode" | "jump_to" | "fire_cart" | "set_level";
export type Fader = "player1" | "player2" | "player3" | "carts";

export interface Studio {
  id: string;
  name: string;
  online: boolean;
  last_seen_at: string;
  ready: boolean;
  in_control: boolean;
  cohost: boolean;
  asking_to_join: boolean;
  guest: boolean;
  /** The key's own person is signed in at this studio PC. */
  yours: boolean;
}

export interface PlayoutCommandOptions extends DryRun {
  /** Release on-air control from the studio holding it first (needs On-air control any time). */
  take_over?: boolean;
}

export interface SentCommand {
  id: string;
  command: PlayoutCommandName;
  engine: "cloud" | "browser";
  as_studio: string | null;
  released_control_from: string | null;
  status: "sent" | "not_sent";
  dry_run?: boolean;
}

export interface CommandStatus {
  id: string;
  command: PlayoutCommandName;
  created_at: string;
  processed_at: string | null;
  status: "waiting" | "done" | "expired";
}

export declare class StationMonster {
  constructor(opts?: ClientOptions);
  raw<T = unknown>(
    method: "GET" | "POST" | "PATCH" | "DELETE",
    path: string,
    opts?: { query?: Record<string, unknown>; body?: unknown; headers?: Record<string, string>; idempotencyKey?: string },
  ): Promise<{ data: T; headers: Headers; status: number }>;
  request<T = unknown>(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, opts?: { query?: Record<string, unknown>; body?: unknown; headers?: Record<string, string>; idempotencyKey?: string }): Promise<T>;
  paginate<T = Row>(page: (cursor?: string) => Promise<Page<T>>): AsyncGenerator<T>;
  watch<T>(fn: () => Promise<T>, onChange: (value: T) => unknown, opts?: { intervalMs?: number; onError?: (e: unknown) => void }): () => void;

  me(): Promise<Row>;
  listStations(): Promise<{ data: Station[] }>;
  getStation(stationId: string): Promise<Station>;
  nowPlaying(stationId: string): Promise<NowPlaying>;
  plays(stationId: string, opts?: { from?: string; to?: string; type?: string; limit?: number; cursor?: string }): Promise<Page>;
  log(stationId: string, date?: string): Promise<{ date: string; data: Row[] }>;
  searchLibrary(stationId: string, opts?: { q?: string; type?: string; limit?: number; cursor?: string }): Promise<Page>;
  shows(stationId: string): Promise<{ data: Row[] }>;
  requests(stationId: string, opts?: { status?: "new" | "done" | "dismissed"; limit?: number; cursor?: string }): Promise<Page>;
  listeners(stationId: string, opts?: { from?: string; to?: string }): Promise<{ from: string; to: string; peak: number; data: Row[] }>;

  playout(stationId: string): Promise<Playout>;
  studios(stationId: string): Promise<{ data: Studio[] }>;
  sendPlayoutCommand(
    stationId: string,
    command: PlayoutCommandName,
    opts?: PlayoutCommandOptions & { player?: number; fade?: boolean; mode?: "auto" | "assist"; log_item_id?: string; cart_id?: string; fader?: Fader; level?: number },
  ): Promise<SentCommand>;
  skip(stationId: string, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  playNext(stationId: string, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  playPlayer(stationId: string, player: number, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  stopPlayer(stationId: string, player: number, opts?: PlayoutCommandOptions & { fade?: boolean }): Promise<SentCommand>;
  pausePlayer(stationId: string, player: number, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  recuePlayer(stationId: string, player: number, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  stopAll(stationId: string, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  setMode(stationId: string, mode: "auto" | "assist", opts?: PlayoutCommandOptions): Promise<SentCommand>;
  jumpTo(stationId: string, logItemId: string, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  fireCart(stationId: string, cartId: string, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  /** 0 = off, 0.75 = the U mark, 1 = top (0 dB). Cloud engine only. */
  setLevel(stationId: string, fader: Fader, level: number, opts?: PlayoutCommandOptions): Promise<SentCommand>;
  setOnAirControl(stationId: string, action: "take" | "hand" | "release", opts?: { studioId?: string; takeOver?: boolean } & DryRun): Promise<Playout>;
  takeControl(stationId: string, studioId: string, opts?: { takeOver?: boolean } & DryRun): Promise<Playout>;
  handControl(stationId: string, studioId: string, opts?: { takeOver?: boolean } & DryRun): Promise<Playout>;
  releaseControl(stationId: string, opts?: { takeOver?: boolean } & DryRun): Promise<Playout>;
  setCohost(stationId: string, studioId: string, on: boolean, opts?: DryRun): Promise<Playout>;
  setMuteAudio(stationId: string, on: boolean, opts?: { studioId?: string } & DryRun): Promise<Playout>;
  setNowPlayingText(stationId: string, text: string | null, opts?: DryRun): Promise<{ override: string | null; text: string | null; dry_run?: boolean }>;
  playoutCommand(stationId: string, commandId: string): Promise<CommandStatus>;
  waitForCommand(stationId: string, commandId: string, opts?: { timeoutMs?: number; intervalMs?: number }): Promise<CommandStatus>;

  addLogEntry(stationId: string, opts: { date: string; mediaId: string; beforeId?: string; hour?: number } & DryRun): Promise<{ data: Row; dry_run?: boolean }>;
  moveLogEntry(stationId: string, itemId: string, opts?: { beforeId?: string; hour?: number; date?: string } & DryRun): Promise<{ data: Row; dry_run?: boolean }>;
  swapLogEntries(stationId: string, itemId: string, withId: string, opts?: DryRun): Promise<{ data: Row[]; dry_run?: boolean }>;
  removeLogEntry(stationId: string, itemId: string, opts?: DryRun): Promise<{ data: Row; dry_run?: boolean }>;

  listResources(q?: string): Promise<{ data: Row[] }>;
  describeResource(resource: string): Promise<Row>;
  listRecords<T = Row>(resource: string, opts?: { filters?: Filters; select?: string; order?: string; count?: boolean; limit?: number; cursor?: string }): Promise<Page<T>>;
  getRecord<T = Row>(resource: string, id: string, opts?: { select?: string }): Promise<{ data: T; etag: string | null }>;
  createRecords<T = Row>(resource: string, records: Row | Row[], opts?: { upsert?: boolean; select?: string } & DryRun): Promise<{ data: T[]; count: number; dry_run?: boolean }>;
  updateRecord<T = Row>(resource: string, id: string, values: Row, opts?: { ifMatch?: string; select?: string } & DryRun): Promise<{ data: T; etag: string | null }>;
  updateRecords<T = Row>(resource: string, filters: Filters, values: Row, opts?: DryRun): Promise<{ data: T[]; count: number; dry_run?: boolean }>;
  deleteRecord<T = Row>(resource: string, id: string, opts?: { ifMatch?: string } & DryRun): Promise<T>;
  deleteRecords<T = Row>(resource: string, filters: Filters, opts?: DryRun): Promise<{ data: T[]; count: number; dry_run?: boolean }>;

  listActions(q?: string): Promise<{ data: Row[] }>;
  callAction<T = unknown>(name: string, args?: Record<string, unknown>, opts?: DryRun): Promise<T>;

  mediaAudio(stationId: string, mediaId: string): Promise<{ url: string; expires_in: number; storage_path: string; title: string | null }>;
  createUpload(stationId: string, opts: { ext: string; size: number }): Promise<{ storage_path: string; storage_provider: string; upload_url: string; method: string; headers: Record<string, string>; max_bytes: number; expires_in: number }>;
  uploadAudio(stationId: string, file: Uint8Array | ArrayBuffer | Blob, opts: { ext: string; contentType?: string }): Promise<{ storage_path: string; storage_provider: string }>;
  addToLibrary(stationId: string, file: Uint8Array | ArrayBuffer | Blob, opts: { ext: string; contentType?: string; title: string; [field: string]: unknown }): Promise<Row>;
}

export declare function verifyWebhook(rawBody: string, signatureHeader: string | null, secret: string, opts?: { toleranceSec?: number }): Promise<boolean>;

export default StationMonster;
