package com.arms.api.util;

import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@NoArgsConstructor
@Slf4j
@Component
public class YamlFileUtils {

    @SuppressWarnings("java:S2647")
    public List<String> getYamlFilesFromDirectory(
            String directoryUrl, String branch, String username, String password) throws Exception {
        List<String> yamlFiles = new ArrayList<>();

        String fileUrl = directoryUrl + "?ref=" + branch;
        log.info("[YamlFileUtils :: getYamlFilesFromDirectory] :: fileUrl => {}", fileUrl);
        // 디렉토리 조회 API 호출
        HttpURLConnection connection = null;

        try {
            connection = (HttpURLConnection) new URL(fileUrl).openConnection();
            String auth = username + ":" + password;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + encodedAuth);

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to fetch directory: " + connection.getResponseMessage());
            }

            // 응답 파싱
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {

                Yaml yaml = new Yaml();
                List<Map<String, Object>> files = yaml.load(reader);

                for (Map<String, Object> fileInfo : files) {
                    String type = (String) fileInfo.get("type");
                    String downloadUrl = (String) fileInfo.get("download_url");
                    String httpsUrl = downloadUrl.replace("http://", "https://");

                    // YAML 파일만 선택
                    if ("file".equals(type) && (downloadUrl.endsWith(".yml") || downloadUrl.endsWith(".yaml"))) {
                        yamlFiles.add(httpsUrl);
                        yamlFiles.add(downloadUrl);
                    }
                }
            }
        } catch (Exception e) {
            log.error("[YamlFileUtils :: getYamlFileUtiils] :: Error while fetching YAML files from directory: {}", e.getMessage());
            // 에러 발생 시 빈 리스트 반환
            return yamlFiles;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return yamlFiles;
    }

    public  String extractFileNameWithoutExtension(String fileUrl) {
        String fullFileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        return fullFileName.substring(0, fullFileName.lastIndexOf('.'));
    }
}
