package ai.decompile.analysis.model.dto;

import ai.decompile.analysis.model.entity.StaticDataLabel;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public record DataLabelResponse(
    UUID id,
    String name,
    String address,
    String segment,
    int size,
    List<DataXrefResponse> dataXrefs) {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static DataLabelResponse from(StaticDataLabel d) {
    return new DataLabelResponse(
        d.getId(),
        d.getName(),
        d.getAddress(),
        d.getSegment(),
        d.getSize(),
        parseDataXrefs(d.getDataXrefs()));
  }

  private static List<DataXrefResponse> parseDataXrefs(String raw) {
    if (Objects.isNull(raw) || raw.isBlank() || "[]".equals(raw.trim())) {
      return Collections.emptyList();
    }

    try {
      var decoded = MAPPER.readValue("\"" + raw + "\"", String.class);
      return MAPPER.readValue(
          decoded,
          MAPPER.getTypeFactory().constructCollectionType(List.class, DataXrefResponse.class));
    } catch (Exception e) {
      return Collections.emptyList();
    }
  }
}
