const fs = require('node:fs');
const axios = require('axios');
const { sleep } = require('./json_utils.cjs');
const { emitEvent } = require('./workspace.cjs');

function resolveModelConfig(env) {
  const apiKey = env.ARK_API_KEY;
  if (!apiKey) throw new Error('缺少 ARK_API_KEY，请在 skill 管理页配置');
  const detectModel = env.DAMAGE_DETECT_MODEL || 'doubao-seed-2-0-pro-260215';
  return {
    apiKey,
    apiUrl: env.ARK_API_URL || 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
    detectModel,
    groundingModel: env.DAMAGE_GROUNDING_MODEL || detectModel,
    reviewModel: env.DAMAGE_REVIEW_MODEL || detectModel,
    bestFrameModel: env.BEST_FRAME_MODEL || detectModel,
  };
}

function encodeImage(filePath) {
  return fs.readFileSync(filePath).toString('base64');
}

async function callVisionApi({ config, model, messages, maxTokens = 2048, temperature = 0.1, timeoutMs = 600000 }) {
  for (let attempt = 1; attempt <= 4; attempt += 1) {
    emitEvent('vision-api', 'request started', { model, attempt, totalAttempts: 4, timeoutMs });
    try {
      const res = await axios.post(config.apiUrl, {
        model,
        messages,
        max_tokens: maxTokens,
        temperature,
      }, {
        timeout: timeoutMs,
        headers: {
          Authorization: `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json',
        },
      });
      const content = res.data?.choices?.[0]?.message?.content || '';
      emitEvent('vision-api', 'request completed', { model, attempt, usage: res.data?.usage });
      return { ok: true, content, usage: res.data?.usage };
    } catch (error) {
      const message = error?.response?.data ? JSON.stringify(error.response.data).slice(0, 1000) : error.message;
      const retryable = /429|TooManyRequests|timeout|ECONNRESET|ETIMEDOUT/i.test(message);
      if (retryable && attempt < 4) {
        await sleep(3000 * attempt);
        continue;
      }
      emitEvent('vision-api', 'request failed', { model, attempt, level: 'error', error: message });
      return { ok: false, error: message };
    }
  }
  return { ok: false, error: 'unknown vision api failure' };
}

function imageContent(filePath) {
  return {
    type: 'image_url',
    image_url: { url: `data:image/jpeg;base64,${encodeImage(filePath)}` },
  };
}

module.exports = {
  resolveModelConfig,
  encodeImage,
  callVisionApi,
  imageContent,
};
