package gc.mda.kcg.collector.aircraft;

import com.fasterxml.jackson.databind.JsonNode;
import gc.mda.kcg.domain.aircraft.AircraftCategory;
import gc.mda.kcg.domain.aircraft.AircraftDto;

import java.util.ArrayList;
import java.util.List;

/**
 * OpenSky Network API 응답 JSON → AircraftDto 변환.
 * 프론트엔드 opensky.ts:parseOpenSkyResponse 이식.
 *
 * 응답 구조: { "time": 1234, "states": [ [icao24, callsign, ..., lat, lng, alt, ...], ... ] }
 * 인덱스: 0=icao24, 1=callsign, 4=lastSeen, 5=lng, 6=lat, 7=altitude(m),
 *         8=onGround, 9=velocity(m/s), 10=heading, 11=verticalRate
 */
public final class OpenSkyParser {

    private OpenSkyParser() {}

    public static List<AircraftDto> parse(JsonNode root) {
        JsonNode states = root.path("states");
        if (states.isMissingNode() || !states.isArray()) {
            return List.of();
        }

        List<AircraftDto> result = new ArrayList<>();

        for (JsonNode s : states) {
            if (!s.isArray() || s.size() < 12) continue;

            // lat(6), lng(5) 필수
            if (s.get(6).isNull() || s.get(5).isNull()) continue;

            String callsign = s.get(1).isNull() ? "" : s.get(1).asText("").trim();
            AircraftCategory category = AircraftClassifier.classifyByCallsign(callsign);

            result.add(AircraftDto.builder()
                    .icao24(s.get(0).asText(""))
                    .callsign(callsign)
                    .lat(s.get(6).asDouble())
                    .lng(s.get(5).asDouble())
                    .altitude(s.get(7).isNull() ? 0 : s.get(7).asDouble())
                    .velocity(s.get(9).isNull() ? 0 : s.get(9).asDouble())
                    .heading(s.get(10).isNull() ? 0 : s.get(10).asDouble())
                    .verticalRate(s.get(11).isNull() ? 0 : s.get(11).asDouble())
                    .onGround(s.get(8).isNull() ? false : s.get(8).asBoolean())
                    .category(category)
                    .lastSeen(s.get(4).isNull() ? System.currentTimeMillis() : s.get(4).asLong() * 1000)
                    .build());
        }
        return result;
    }
}
