package ai.decompile.job.service.handler;

import ai.decompile.die.model.DieResultParser;
import ai.decompile.die.service.DiecService;
import ai.decompile.job.model.entity.Job;
import ai.decompile.job.model.enums.JobStatus;
import ai.decompile.job.model.enums.JobType;
import ai.decompile.workspace.service.BinaryService;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Log4j2
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "app.docker.enabled", havingValue = "true")
public class AnalyzeFileHandler implements JobHandler {
  private final DiecService diecService;
  private final DieResultParser dieResultParser;
  private final BinaryService binaryService;
  private final ObjectMapper objectMapper;

  @Override
  public void process(Job job) {
    log.info(
        "Processing ANALYZE_FILE job {} for binary {} in project {}",
        job.getId(),
        job.getBinaryId(),
        job.getProjectId());

    var filePath = binaryService.getBinaryFilePath(job.getBinaryId());
    var result = diecService.analyze(filePath);
    var parsed = dieResultParser.parse(result);

    binaryService.updateAnalysisInfo(
        job.getBinaryId(), parsed.fileType(), parsed.architecture(), parsed.compiler());

    job.setResult(toJson(Map.of("raw", result, "info", parsed)));
    job.setStatus(JobStatus.COMPLETED);

    log.info(
        "Job {} completed. fileType={}, arch={}, compiler={}",
        job.getId(),
        parsed.fileType(),
        parsed.architecture(),
        parsed.compiler());
  }

  @Override
  public JobType supportedType() {
    return JobType.ANALYZE_FILE;
  }

  private String toJson(Object obj) {
    try {
      return objectMapper.writeValueAsString(obj);
    } catch (Exception e) {
      log.warn("Failed to serialize result to JSON", e);
      return null;
    }
  }
}
