/**
 * Adapter that wraps the RC bridge's requestApproval() into a callback-based
 * interface compatible with the interactive permission handler's race pattern.
 *
 * The interactive handler races multiple approval sources (terminal UI, CCR
 * bridge, channels, hooks, classifier). This adapter lets the RC mobile
 * bridge participate as another racer.
 */
import { randomUUID } from 'crypto'
import { isRCActive, requestApproval } from './bridge.js'

export type RCPermissionCallbacks = {
  /** Returns true when at least one RC mobile client is connected. */
  isActive(): boolean
  /**
   * Send a permission request to connected RC clients. Returns a promise
   * that resolves when a client responds, or rejects if cancelled.
   */
  requestApproval(
    sessionId: string,
    toolName: string,
    input: Record<string, unknown>,
    description?: string,
  ): { requestId: string; promise: Promise<'allow' | 'deny'> }
}

/**
 * Creates an RCPermissionCallbacks instance backed by the RC bridge module.
 * The sessionId is captured at creation time (one per SANDCODE session).
 */
export function createRCPermissionCallbacks(
  sessionId: string,
): RCPermissionCallbacks {
  return {
    isActive: isRCActive,
    requestApproval(
      _sessionId: string,
      toolName: string,
      input: Record<string, unknown>,
      description?: string,
    ) {
      const requestId = randomUUID()
      const promise = requestApproval(
        sessionId,
        requestId,
        toolName,
        input,
        description,
      )
      return { requestId, promise }
    },
  }
}
