package cn.iocoder.yudao.module.llm.utils;

import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.URLUtil;
import cn.iocoder.yudao.module.llm.dal.dataobject.dataset.DatasetQuestionDO;
import cn.iocoder.yudao.module.llm.utils.vo.CsvDataSetVO;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class DataSetReadFileUtils {
    public static HttpURLConnection readFile (String filePath) {
        try {
            URL url = new URL(filePath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection;
            } else {
                System.out.println("Failed to fetch file. Server returned HTTP code: " + connection.getResponseCode());
            }
            connection.disconnect();
        } catch (Exception e) {
            System.out.println("Error fetching file from URL: " + e.getMessage());
        }
        return null;
    }

    /**
     * 读取并解析 CSV 文件
     *
     * @param csvUrl CSV文件的URL
     * @return CSV 文件解析对象
     */
    public static List<CsvDataSetVO> readParseCsv (String csvUrl) throws IOException, CsvValidationException {

        List<CsvDataSetVO> dataSetVos;

        // 创建 URL 对象
        URL url = URLUtil.url(csvUrl);

        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()))) {
            CsvReader reader = CsvUtil.getReader(bufferedReader);
            dataSetVos = reader.read(bufferedReader, CsvDataSetVO.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 返回解析后的对象
        return dataSetVos;
    }


    public static Workbook readXlsxFromUrl(String filePath) {
        HttpURLConnection connection = readFile(filePath);
        if (connection != null) {
            try (InputStream inputStream = connection.getInputStream()) {
                return new XSSFWorkbook(inputStream);
            } catch (Exception e) {
                System.out.println("Error reading XLSX file from URL: " + e.getMessage());
            } finally {
                connection.disconnect();
            }
        }
        return null;
    }
}
