import { RetryConfig } from '../utils/resilience.js';

/**
 * Type definitions for browser automation tool
 */

/**
 * Available browser automation models
 */
type BrowserModel = 'gemini-3-flash-preview' | 'morph-computer-use-v0' | 'morph-computer-use-v1';
/**
 * Configuration for the browser worker service
 */
interface BrowserConfig {
    /** Browser worker API URL (default: https://browser.morphllm.com) */
    apiUrl?: string;
    /** Morph API key for authentication (required in production) */
    apiKey?: string;
    /** Request timeout in milliseconds (default: 1000000) */
    timeout?: number;
    /** Retry configuration for API calls */
    retryConfig?: RetryConfig;
    /** Enable debug logging (default: false) */
    debug?: boolean;
}
/**
 * Authentication credentials for site login (follows browser-use sensitive_data pattern)
 */
interface AuthCredentials {
    /** Username/email for login */
    username?: string;
    /** Password for login */
    password?: string;
    /** Cookies in any JSON format, passed through to browser-use */
    cookies?: any;
}
/**
 * Input parameters for browser automation task
 */
interface BrowserTaskInput {
    /** Natural language description of what to do */
    task?: string;
    /**
     * Optional PR diff used to generate a deterministic test plan on the backend.
     * If provided, `task` is treated as optional human instructions / focus areas.
     */
    diff?: string;
    /** Starting URL (e.g., https://3000-xyz.e2b.dev) */
    url?: string;
    /** Maximum number of browser actions to take (1-50, default: 10) */
    maxSteps?: number;
    /** Model to use for task execution (default: morph-computer-use-v0) */
    model?: BrowserModel;
    /** Browserless region: 'sfo' (US West) or 'lon' (Europe) */
    region?: 'sfo' | 'lon';
    /** Enable stealth mode to avoid bot detection (default: true) */
    stealth?: boolean;
    /** Browser viewport width (default: 1280) */
    viewportWidth?: number;
    /** Browser viewport height (default: 720) */
    viewportHeight?: number;
    /** User-defined reference/tracking ID (e.g., "PR-1234", "jira-PROJ-567") */
    externalId?: string;
    /** Optional repository database ID (UUID) to associate with this session - for internal use */
    repoId?: string;
    /** Optional repository full name (e.g., "owner/repo") - for external SDK users */
    repoFullName?: string;
    /** Optional commit UUID to associate with this session */
    commitId?: string;
    /** Record session video to S3 (default: false) */
    recordVideo?: boolean;
    /** Video width (default: 1280) */
    videoWidth?: number;
    /** Video height (default: 720) */
    videoHeight?: number;
    /** Enable window resizing for responsive/mobile testing. Disables stealth mode. (default: false) */
    allowResizing?: boolean;
    /** Serialized structured output schema (internal use) */
    structuredOutput?: string;
    /** Site authentication - global credentials or per-domain dict (follows browser-use pattern) */
    auth?: AuthCredentials | Record<string, AuthCredentials>;
    /** Profile ID - restore cookies/localStorage from a saved browser profile */
    profileId?: string;
    /**
     * Query parameters to force-append to ALL navigation URLs.
     * Used for Vercel deployment protection bypass.
     * Example: { 'x-vercel-protection-bypass': 'secret123', 'x-vercel-set-bypass-cookie': 'true' }
     */
    forceQueryParams?: Record<string, string>;
}
/**
 * Input with Zod schema for structured output
 */
interface BrowserTaskInputWithSchema<T> extends Omit<BrowserTaskInput, 'structuredOutput'> {
    /** Zod schema for structured output */
    schema: any;
}
/**
 * Result from executing a browser task
 */
interface BrowserTaskResult {
    /** Whether the task completed successfully */
    success: boolean;
    /** Task result or findings */
    result?: string;
    /** Error message if task failed */
    error?: string;
    /** Number of browser actions taken */
    stepsTaken?: number;
    /** Total execution time in milliseconds */
    executionTimeMs?: number;
    /** All URLs visited during execution */
    urls?: (string | null)[];
    /** Names of all actions executed */
    actionNames?: string[];
    /** Per-step errors (null for steps without errors) */
    errors?: (string | null)[];
    /** All model actions with parameters */
    modelActions?: any[];
    /** Whether agent marked task as done */
    isDone?: boolean;
    /** Truncated action history with essential fields */
    actionHistory?: any[][];
    /** All action results */
    actionResults?: any[];
    /** Whether any errors occurred */
    hasErrors?: boolean;
    /** Total number of steps executed */
    numberOfSteps?: number;
    /** Judge validation result if available */
    judgement?: {
        reasoning?: string;
        verdict: boolean;
        failure_reason?: string;
        impossible_task?: boolean;
        reached_captcha?: boolean;
    };
    /** Whether judge validated the execution */
    isValidated?: boolean;
    /** UUID of saved replay record (if session replay enabled) */
    replayId?: string;
    /** Browserless replay URL (if session replay enabled) */
    replayUrl?: string;
    /** Recording ID (if recordVideo=true) */
    recordingId?: string;
    /** Recording status: PENDING, PROCESSING, COMPLETED, ERROR */
    recordingStatus?: string;
    /** Task ID for async task tracking */
    taskId?: string;
    /** Task status: pending, running, completed, failed */
    status?: string;
    /** Structured output (JSON string) */
    output?: string;
    /** Live session debug URL for real-time viewing (WebRTC streaming) */
    debugUrl?: string;
}
/**
 * Configuration for live session viewing
 */
interface LiveSessionOptions {
    /** Enable or disable remote control (default: true for headful, varies for headless) */
    interactive?: boolean;
    /** UI theme: 'dark' or 'light' (headless only, default: 'dark') */
    theme?: 'dark' | 'light';
    /** Show or hide navigation controls (headless only, default: true) */
    showControls?: boolean;
    /** Focus view on specific page/tab ID (headless only) */
    pageId?: string;
    /** Display specific tab by index (headless only) */
    pageIndex?: string;
}
/**
 * Configuration for iframe generation
 */
interface IframeOptions extends LiveSessionOptions {
    /** Iframe width (default: '100%') */
    width?: string | number;
    /** Iframe height (default: '600px') */
    height?: string | number;
    /** Additional inline styles */
    style?: string;
    /** CSS class name */
    className?: string;
}
/**
 * Task result with convenience methods for async execution
 */
interface BrowserTaskWithPromise extends BrowserTaskResult {
    taskId: string;
    /** Live URL to watch task execution in real-time */
    liveUrl: string;
    /** Wait for task completion */
    complete: (pollConfig?: {
        interval?: number;
        timeout?: number;
    }) => Promise<BrowserTaskResult>;
    /** Get live session URL with optional parameters (Steel.dev) - throws if debugUrl not available */
    getLiveUrl: (options?: LiveSessionOptions) => string;
    /** Get iframe HTML for embedding live session - throws if debugUrl not available */
    getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
    /** Get complete embed code snippet - throws if debugUrl not available */
    getEmbedCode: () => string;
}
/**
 * Task result with schema validation
 */
interface BrowserTaskWithPromiseAndSchema<T> extends BrowserTaskResult {
    taskId: string;
    /** Live URL to watch task execution in real-time */
    liveUrl: string;
    /** Parsed and validated output */
    parsed: T | null;
    /** Wait for task completion with schema validation */
    complete: (pollConfig?: {
        interval?: number;
        timeout?: number;
    }) => Promise<BrowserTaskResult & {
        parsed: T | null;
    }>;
    /** Get live session URL with optional parameters - throws if debugUrl not available */
    getLiveUrl: (options?: LiveSessionOptions) => string;
    /** Get iframe HTML for embedding live session - throws if debugUrl not available */
    getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
    /** Get complete embed code snippet - throws if debugUrl not available */
    getEmbedCode: () => string;
}
/**
 * Recording status and metadata
 */
interface RecordingStatus {
    /** Recording ID */
    id: string;
    /** Current status */
    status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'ERROR';
    /** Presigned S3 URL for rrweb replay JSON (interactive DOM replay) */
    replayUrl?: string;
    /** Presigned S3 URL for network logs (NDJSON format) */
    networkUrl?: string;
    /** Presigned S3 URL for console logs (NDJSON format) */
    consoleUrl?: string;
    /** Presigned S3 URL for native browser video (WebM or MP4 format, real-time recording) */
    videoUrl?: string;
    /** Final AI summary from the browser agent */
    result?: string;
    /** Total rrweb events captured */
    totalEvents?: number;
    /** Total bytes of all files */
    fileSize?: number;
    /** Duration in milliseconds */
    duration?: number;
    /** Error message if status=ERROR */
    error?: string;
    /** When recording was created */
    createdAt: string;
}
/**
 * Browser error with screenshot captured at error time
 */
interface BrowserError {
    /** Error type: console error or network error */
    type: 'console' | 'network';
    /** Error message */
    message: string;
    /** URL where error occurred */
    url?: string;
    /** CDP timestamp in seconds since browser start */
    timestamp: number;
    /** Presigned S3 URL to screenshot JPEG (captured 500ms after error) */
    screenshotUrl?: string;
    /** When screenshot was captured (Unix timestamp) */
    capturedAt?: number;
    /** HTTP status code (for network errors) */
    status?: number;
}
/**
 * Response from getErrors()
 */
interface ErrorsResponse {
    /** Recording ID */
    recordingId: string;
    /** Total number of errors */
    totalErrors: number;
    /** Errors with real-time screenshots */
    errors: BrowserError[];
}
/**
 * Options for WebP generation
 */
interface WebpOptions {
    /** Maximum duration in seconds (1-120, default: 60) */
    maxDuration?: number;
    /** Frame rate (5-30, default: 15) */
    fps?: number;
    /** Output width in pixels (320-1920, default: 780) */
    width?: number;
    /** Quality (10-100, default: 65) */
    quality?: number;
    /** Enable auto-zoom that follows click/input actions (default: false) */
    autoZoom?: boolean;
    /** Maximum file size in MB (0.5-50). Uses iterative reduction to guarantee budget. */
    maxSizeMb?: number;
}
/**
 * Response from getWebp()
 */
interface WebpResponse {
    /** Presigned S3 URL for the WebP file */
    webpUrl: string;
    /** Whether the WebP was served from cache */
    cached: boolean;
    /** Width of the WebP (may differ from requested if budget-constrained) */
    width: number;
    /** Frame rate of the WebP (may differ from requested if budget-constrained) */
    fps: number;
    /** Max duration used (may differ from requested if budget-constrained) */
    maxDuration: number;
    /** File size in bytes */
    fileSize?: number;
    /** Max size budget in MB (if specified) */
    maxSizeMb?: number;
    /** Whether the file fits within the budget */
    budgetMet?: boolean;
    /** Quality setting used (may differ from requested if budget-constrained) */
    qualityUsed?: number;
    /** Number of encoding attempts needed to meet budget */
    attempts?: number;
}
/**
 * Recording with convenience methods
 */
interface RecordingWithMethods extends RecordingStatus {
    /** Get animated WebP preview */
    getWebp: (options?: WebpOptions) => Promise<WebpResponse>;
    /** Get errors with screenshots */
    getErrors: () => Promise<ErrorsResponse>;
}

export type { AuthCredentials, BrowserConfig, BrowserError, BrowserModel, BrowserTaskInput, BrowserTaskInputWithSchema, BrowserTaskResult, BrowserTaskWithPromise, BrowserTaskWithPromiseAndSchema, ErrorsResponse, IframeOptions, LiveSessionOptions, RecordingStatus, RecordingWithMethods, WebpOptions, WebpResponse };
