package com.caliverse.admin.domain.datacomponent;

import com.caliverse.admin.global.common.exception.MetaDataException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class JsonFileReader {
    @Value("${caliverse.metadata.path}")
    private String metaDataPath;

    private final ObjectMapper objectMapper;

    public JsonFileReader() {
        this.objectMapper = new ObjectMapper();
    }

    public List<Map<String, Object>> readJsonFile(String fileName, String listName) {
        List<Map<String, Object>> resultMap = new ArrayList<>();

        try {
            File file = new File(metaDataPath, fileName);
            log.info("loadDataFromJsonFile path: {}", file.getPath());

            if (!file.exists()) {
                log.error("File not found: {}", fileName);
                return null;
            }

            String fileContent = readFileAsString(file);
            JsonNode rootNode = objectMapper.readTree(fileContent);
            JsonNode listNode = rootNode.get(listName);

            if (listNode == null) {
                throw new MetaDataException("List name not found: " + listName);
            }

            resultMap = objectMapper.readValue(
                    listNode.toString(),
                    new TypeReference<>() {
                    }
            );

            log.debug("Successfully parsed JSON file: {}, items count: {}", fileName, resultMap.size());

        } catch (JsonProcessingException e) {
            log.error("Failed to parse JSON from file: {}", fileName, e);
            throw new MetaDataException("Failed to parse JSON from file: " + fileName, e);
        } catch (IOException e) {
            log.error("Failed to read file: {}", fileName, e);
            throw new MetaDataException("Failed to read file: " + fileName, e);
        }

        return resultMap;
    }

    private String readFileAsString(File file) throws IOException {
        StringBuilder fileContents = new StringBuilder((int)file.length());
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            String line;
            while((line = br.readLine()) != null) {
                fileContents.append(line);
            }
        }
        return fileContents.toString();
    }
}
