// E2B Sandbox API 客户端

import { supabase } from '@/integrations/supabase/client';
import type { 
  SandboxExecutionResult, 
  SandboxExecutionRequest,
  SandboxStatusEvent 
} from '@/types/sandbox';

// 执行沙盒任务
export async function executeSandbox(
  request: SandboxExecutionRequest
): Promise<SandboxExecutionResult> {
  const { data, error } = await supabase.functions.invoke('sandbox-execute', {
    body: request
  });

  if (error) {
    throw new Error(`沙盒执行失败: ${error.message}`);
  }

  return data as SandboxExecutionResult;
}

// 获取执行结果
export async function getSandboxResult(
  executionId: string
): Promise<SandboxExecutionResult> {
  const { data, error } = await supabase.functions.invoke('sandbox-result', {
    body: { executionId }
  });

  if (error) {
    throw new Error(`获取结果失败: ${error.message}`);
  }

  return data as SandboxExecutionResult;
}

// 取消执行
export async function cancelSandboxExecution(
  executionId: string
): Promise<{ success: boolean }> {
  const { data, error } = await supabase.functions.invoke('sandbox-cancel', {
    body: { executionId }
  });

  if (error) {
    throw new Error(`取消执行失败: ${error.message}`);
  }

  return data;
}

// 下载沙盒生成的文件
export async function downloadSandboxFile(
  executionId: string,
  fileId: string
): Promise<Blob> {
  const { data, error } = await supabase.functions.invoke('sandbox-download', {
    body: { executionId, fileId }
  });

  if (error) {
    throw new Error(`下载文件失败: ${error.message}`);
  }

  // 如果返回base64，转换为Blob
  if (data.base64) {
    const binaryString = atob(data.base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    return new Blob([bytes], { type: data.mimeType });
  }

  return data;
}

// 订阅执行状态更新
export function subscribeSandboxStatus(
  executionId: string,
  onUpdate: (event: SandboxStatusEvent) => void
): () => void {
  const channel = supabase
    .channel(`sandbox:${executionId}`)
    .on('broadcast', { event: 'status' }, (payload) => {
      onUpdate(payload.payload as SandboxStatusEvent);
    })
    .subscribe();

  return () => {
    supabase.removeChannel(channel);
  };
}

// 获取执行历史
export async function getSandboxHistory(
  agentType?: string,
  limit = 20
): Promise<SandboxExecutionResult[]> {
  const { data, error } = await supabase.functions.invoke('sandbox-history', {
    body: { agentType, limit }
  });

  if (error) {
    throw new Error(`获取历史失败: ${error.message}`);
  }

  return data as SandboxExecutionResult[];
}
