import axios from 'axios';
import fs from 'fs';
import path from 'path';

const BACKEND_SERVER_URL = process.env.BACKEND_SERVER_URL;
const BACKEND_SITE_NAME = process.env.BACKEND_SITE_NAME;
const PUBLIC_FILES_DIR = path.join(process.cwd(), 'public/files');

// 确保目录存在
if (!fs.existsSync(PUBLIC_FILES_DIR)) {
  fs.mkdirSync(PUBLIC_FILES_DIR, { recursive: true });
}

// 下载图片到本地public/files目录，返回本地路径
async function downloadToLocal(fileUrl) {
  try {
    // 判断是否为完整URL
    let fullUrl = fileUrl;
    if (!/^https?:\/\//.test(fileUrl)) {
      // 相对路径，拼接服务器地址
      fullUrl = `${BACKEND_SERVER_URL}${fileUrl}`;
    }
    // 取文件名
    const fileName = path.basename(fullUrl.split('?')[0]);
    const localPath = path.join(PUBLIC_FILES_DIR, fileName);
    const localUrl = `/files/${fileName}`;
    // 如果本地已存在则不再下载
    if (!fs.existsSync(localPath)) {
      const response = await axios.get(fullUrl, { responseType: 'stream' });
      await new Promise((resolve, reject) => {
        const writer = fs.createWriteStream(localPath);
        response.data.pipe(writer);
        writer.on('finish', resolve);
        writer.on('error', reject);
      });
    }
    return localUrl;
  } catch (e) {
    return fileUrl; // 下载失败返回原始路径
  }
}

export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);
    const component_name = searchParams.get('component_name');
    if (!component_name) {
      return Response.json({ error: '缺少component_name参数' }, { status: 400 });
    }
    const response = await axios.get(
      `${BACKEND_SERVER_URL}/api/action/jsite.api.v1.get_component_data`,
      { params: { component_name, site_name: BACKEND_SITE_NAME } }
    );
    let data = response.data.message?.data || {};

    // 处理主图片字段和icon、file_src
    for (const key of ['image', 'image_1', 'image_2', 'icon', 'file_src']) {
      if (data[key]) {
        data[key] = await downloadToLocal(data[key]);
      }
    }
    // 处理items数组中的item_image、item_video_src、item_file_src、item_icon
    if (Array.isArray(data.items)) {
      for (const item of data.items) {
        if (item.item_image) {
          item.item_image = await downloadToLocal(item.item_image);
        }
        if (item.item_video_src) {
          // 只有相对路径才下载到本地，完整URL直接返回原始URL
          if (!/^https?:\/\//.test(item.item_video_src)) {
            item.item_video_src = await downloadToLocal(item.item_video_src);
          }
        }
        if (item.item_file_src) {
          item.item_file_src = await downloadToLocal(item.item_file_src);
        }
        if (item.item_icon) {
          item.item_icon = await downloadToLocal(item.item_icon);
        }
      }
    }
    return Response.json({ data });
  } catch (error) {
    return Response.json(
      { error: error.message, detail: error?.response?.data || null },
      { status: 500 }
    );
  }
} 