package com.lingniu.ingest.vehiclestat;

import com.google.protobuf.InvalidProtocolBufferException;
import com.lingniu.ingest.api.consumer.EnvelopeIngestResult;
import com.lingniu.ingest.api.consumer.EnvelopeIngestor;
import com.lingniu.ingest.sink.kafka.proto.VehicleEnvelope;
import com.lingniu.ingest.vehiclestat.jt808.Jt808MileageStreamProcessor;

public final class VehicleStatEnvelopeIngestor implements EnvelopeIngestor {

    private final Jt808MileageStreamProcessor jt808MileageProcessor;

    public VehicleStatEnvelopeIngestor(Jt808MileageStreamProcessor jt808MileageProcessor) {
        if (jt808MileageProcessor == null) {
            throw new IllegalArgumentException("jt808MileageProcessor must not be null");
        }
        this.jt808MileageProcessor = jt808MileageProcessor;
    }

    public void ingest(byte[] kafkaValue) {
        VehicleEnvelope envelope = parse(kafkaValue);
        if (!envelope.hasTelemetrySnapshot()) {
            return;
        }
        if ("JT808".equalsIgnoreCase(envelope.getSource())) {
            jt808MileageProcessor.process(envelope);
        }
    }

    @Override
    public EnvelopeIngestResult tryIngest(byte[] kafkaValue) {
        VehicleEnvelope envelope = null;
        try {
            envelope = parse(kafkaValue);
            if (!envelope.hasTelemetrySnapshot()) {
                return EnvelopeIngestResult.skipped(
                        envelope.getEventId(), envelope.getVin(), "envelope telemetry_snapshot is required");
            }
            if ("JT808".equalsIgnoreCase(envelope.getSource())) {
                jt808MileageProcessor.process(envelope);
                return EnvelopeIngestResult.processed(envelope.getEventId(), envelope.getVin());
            }
            return EnvelopeIngestResult.skipped(
                    envelope.getEventId(), envelope.getVin(), "vehicle-stat only accepts JT808 telemetry");
        } catch (IllegalArgumentException ex) {
            return envelope == null
                    ? EnvelopeIngestResult.invalid(ex.getMessage())
                    : EnvelopeIngestResult.skipped(envelope.getEventId(), envelope.getVin(), ex.getMessage());
        }
    }

    private static VehicleEnvelope parse(byte[] kafkaValue) {
        if (kafkaValue == null || kafkaValue.length == 0) {
            throw new IllegalArgumentException("VehicleEnvelope bytes must not be empty");
        }
        try {
            return VehicleEnvelope.parseFrom(kafkaValue);
        } catch (InvalidProtocolBufferException ex) {
            throw new IllegalArgumentException("VehicleEnvelope bytes are invalid", ex);
        }
    }
}
