// MinerU API 客户端

class MinerUClient {
  constructor(options = {}) {
    this.apiUrl = options.apiUrl || 'http://localhost:8080/generate';
    this.timeout = options.timeout || 30000;
  }

  async extractContent(imageBytes, prompt = '请准确提取图中所有可见文字内容，保持原始段落结构') {
    try {
      const encodedImage = btoa(imageBytes);
      const payload = {
        image: encodedImage,
        prompt: prompt
      };

      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload),
        timeout: this.timeout
      });

      if (!response.ok) {
        throw new Error(`API 错误: ${response.status} ${response.statusText}`);
      }

      const result = await response.json();
      return result.text || '';
    } catch (error) {
      console.error('MinerU API 调用失败:', error);
      throw error;
    }
  }

  async batchExtract(images, prompt) {
    const results = [];
    for (let i = 0; i < images.length; i++) {
      try {
        const result = await this.extractContent(images[i], prompt);
        results.push({
          page: i + 1,
          content: result,
          status: 'success'
        });
      } catch (error) {
        results.push({
          page: i + 1,
          content: '',
          status: 'error',
          error: error.message
        });
      }
      // 添加延迟避免API限流
      if (i < images.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
    return results;
  }
}

export const mineruClient = new MinerUClient();
