package ai.decompile.ai.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Objects;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;

@Log4j2
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class AiUtils {
  public static String truncate(String text, int maxChars) {
    if (Objects.isNull(text) || text.length() <= maxChars) {
      return Objects.nonNull(text) ? text : "";
    }

    return text.substring(0, maxChars) + "\n... [truncated]";
  }

  public static String orUnknown(String value) {
    return Objects.nonNull(value) ? value : "unknown";
  }

  public static int estimateTokens(String text) {
    return Objects.nonNull(text) ? (int) Math.ceil(text.length() / 3.5) : 0;
  }

  public static String toVectorString(float[] embedding) {
    var sb = new StringBuilder("[");
    for (var i = 0; i < embedding.length; i++) {
      if (i > 0) {
        sb.append(",");
      }

      sb.append(embedding[i]);
    }

    return sb.append("]").toString();
  }

  public static String toJson(ObjectMapper mapper, Object obj) {
    try {
      return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      log.warn("Failed to serialize object to JSON: {}", e.toString());
      return "{}";
    }
  }
}
