package com.dne.ems.repository.impl;

import com.dne.ems.dto.AqiDistributionDTO;
import com.dne.ems.dto.AqiHeatmapPointDTO;
import com.dne.ems.dto.TrendDataPointDTO;
import com.dne.ems.model.AqiData;
import com.dne.ems.repository.AqiDataRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Repository
@Primary
public class JsonAqiDataRepositoryImpl implements AqiDataRepository {

    private static final String FILE_NAME = "aqi_data.json";
    private final JsonStorageService jsonStorageService;
    private final List<AqiData> cache = new ArrayList<>();
    private final AtomicLong idCounter = new AtomicLong(0);

    public JsonAqiDataRepositoryImpl(JsonStorageService jsonStorageService) {
        this.jsonStorageService = jsonStorageService;
    }

    @PostConstruct
    public void init() {
        List<AqiData> data = jsonStorageService.readData(FILE_NAME, new TypeReference<>() {});
        synchronized (cache) {
            cache.addAll(data);
            long maxId = data.stream()
                              .mapToLong(AqiData::getId)
                              .max()
                              .orElse(0L);
            idCounter.set(maxId);
        }
    }

    @Override
    public AqiData save(AqiData aqiData) {
        synchronized (cache) {
            if (aqiData.getId() == null) {
                aqiData.setId(idCounter.incrementAndGet());
                cache.add(aqiData);
            } else {
                cache.removeIf(a -> a.getId().equals(aqiData.getId()));
                cache.add(aqiData);
            }
            jsonStorageService.writeData(FILE_NAME, cache);
            return aqiData;
        }
    }

    @Override
    public List<AqiData> saveAll(Iterable<AqiData> aqiData) {
        synchronized (cache) {
            List<AqiData> savedData = StreamSupport.stream(aqiData.spliterator(), false)
                .map(this::save)
                .collect(Collectors.toList());
            return savedData;
        }
    }
    
    @Override
    public void deleteAll() {
        synchronized(cache) {
            cache.clear();
            jsonStorageService.writeData(FILE_NAME, cache);
        }
    }
    
    @Override
    public List<AqiData> findAll() {
        synchronized(cache) {
            return new ArrayList<>(cache);
        }
    }

    @Override
    public long count() {
        synchronized(cache) {
            return cache.size();
        }
    }

    @Override
    public List<AqiDistributionDTO> getAqiDistribution() {
        synchronized (cache) {
            return cache.stream()
                .collect(Collectors.groupingBy(this::getAqiCategory, Collectors.counting()))
                .entrySet().stream()
                .map(entry -> new AqiDistributionDTO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        }
    }

    @Override
    public List<TrendDataPointDTO> getMonthlyExceedanceTrend(LocalDateTime startDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        synchronized (cache) {
            List<TrendDataPointDTO> trendData = cache.stream()
                .filter(a -> a.getAqiValue() > 100 && !a.getRecordTime().isBefore(startDate))
                .collect(Collectors.groupingBy(
                    a -> a.getRecordTime().format(formatter),
                    Collectors.counting()
                ))
                .entrySet().stream()
                .map(entry -> new TrendDataPointDTO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

            trendData.sort(Comparator.comparing(dto -> dto.getYearMonth()));

            return trendData;
        }
    }

    @Override
    public List<AqiHeatmapPointDTO> getAqiHeatmapData() {
        synchronized (cache) {
            return cache.stream()
                .filter(a -> a.getGrid() != null && a.getGrid().getGridX() != null && a.getGrid().getGridY() != null)
                .collect(Collectors.groupingBy(
                    a -> new AqiHeatmapPointDTO(a.getGrid().getGridX(), a.getGrid().getGridY(), 0.0),
                    Collectors.averagingDouble(AqiData::getAqiValue)
                ))
                .entrySet().stream()
                .map(entry -> new AqiHeatmapPointDTO(entry.getKey().gridX(), entry.getKey().gridY(), entry.getValue()))
                .collect(Collectors.toList());
        }
    }
    
    private String getAqiCategory(AqiData data) {
        int aqi = data.getAqiValue();
        if (aqi <= 50) return "Good";
        if (aqi <= 100) return "Moderate";
        if (aqi <= 150) return "Unhealthy for Sensitive Groups";
        if (aqi <= 200) return "Unhealthy";
        if (aqi <= 300) return "Very Unhealthy";
        return "Hazardous";
    }
} 