package com.cmvr.inspection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cmvr.common.config.properties.MinioProperties;
import com.cmvr.common.core.minio.MinioService;
import com.cmvr.device.service.InspectionAlertListenService;
import com.cmvr.inspection.domain.InspectionTaskInstance;
import com.cmvr.inspection.domain.InspectionDetectionAlert;
import com.cmvr.inspection.domain.dto.alert.AlertEnvelope;
import com.cmvr.inspection.domain.dto.alert.AlertImage;
import com.cmvr.inspection.exception.DetectionAlertBadRequestException;
import com.cmvr.inspection.exception.DetectionAlertTemporaryException;
import com.cmvr.inspection.mapper.InspectionDetectionAlertMapper;
import com.cmvr.inspection.mapper.InspectionTaskInstanceMapper;
import com.cmvr.inspection.service.IInspectionDetectionAlertService;
import com.cmvr.inspection.service.IInspectionResultService;
import tools.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.List;

/**
 * PPE 违规报警接收业务实现。
 *
 * 数据库唯一索引是并发幂等的最终保障；业务预查用于减少重复请求的无效写入。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InspectionDetectionAlertServiceImpl implements IInspectionDetectionAlertService
{
    private static final String SUPPORTED_SCHEMA = "DetectionAlert/v1";
    private static final String IMAGE_ENCODING_BASE64 = "base64";
    private static final String IMAGE_OBJECT_PREFIX = "inspection/detection-alerts";
    private static final int MAX_EVENT_ID_LENGTH = 128;
    private static final int MAX_IMAGE_BYTES = 10 * 1024 * 1024;
    private static final int MAX_BASE64_LENGTH = (MAX_IMAGE_BYTES * 4 / 3) + 8;

    private final InspectionDetectionAlertMapper alertMapper;
    private final MinioService minioService;
    private final MinioProperties minioProperties;
    private final ObjectMapper objectMapper;
    private final InspectionAlertListenService inspectionAlertListenService;
    private final InspectionTaskInstanceMapper taskInstanceMapper;
    private final IInspectionResultService inspectionResultService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receive(AlertEnvelope envelope, String requestIdempotencyKey)
    {
        String eventId = validateAndResolveEventId(envelope);
        String idempotencyKey = trimToNull(requestIdempotencyKey);

        // 工作流未开启对应 IP + 事件类型监听时，报警只确认接收，不做持久化。
        List<InspectionAlertListenService.ListenSubscription> matchedSubscriptions =
                inspectionAlertListenService.matchSubscriptions(
                        envelope.getGrpcIp(), envelope.getPayload().getLabels());
        if (matchedSubscriptions.isEmpty())
        {
            log.info("忽略未监听的PPE报警，eventId={}，grpcIp={}，labels={}",
                    eventId, envelope.getGrpcIp(), envelope.getPayload().getLabels());
            return false;
        }

        if (exists(eventId))
        {
            log.info("忽略重复PPE报警，eventId={}", eventId);
            return false;
        }

        InspectionDetectionAlert alert = buildAlert(envelope, idempotencyKey);
        StoredImage storedImage = null;
        try
        {
            alertMapper.insert(alert);

            AlertImage image = envelope.getPayload().getImage();
            if (image != null)
            {
                storedImage = uploadImage(alert.getId(), image);
                alert.setImagePath(storedImage.url);
                if (alertMapper.updateById(alert) != 1)
                {
                    throw new DetectionAlertTemporaryException("更新报警图片地址失败");
                }
            }

            for (InspectionAlertListenService.ListenSubscription subscription : matchedSubscriptions)
            {
                InspectionTaskInstance taskInstance = findTaskInstance(subscription.getFlowInstanceId());
                if (taskInstance == null)
                {
                    log.warn("PPE报警未找到巡检任务实例，eventId={}，flowInstanceId={}",
                            eventId, subscription.getFlowInstanceId());
                }
                inspectionResultService.recordPpeResult(alert, subscription, taskInstance);
            }

            log.info("PPE报警接收成功，alertId={}，eventId={}，sourceId={}",
                    alert.getId(), eventId, envelope.getSourceId());
            return true;
        }
        catch (RuntimeException ex)
        {
            // 数据库事务无法回滚 MinIO，对后续步骤失败时主动删除已上传对象。
            if (storedImage != null)
            {
                deleteUploadedImageQuietly(storedImage.objectName);
            }
            throw ex;
        }
    }

    private InspectionTaskInstance findTaskInstance(String flowInstanceId)
    {
        if (StringUtils.isBlank(flowInstanceId))
        {
            return null;
        }
        return taskInstanceMapper.selectOne(new LambdaQueryWrapper<InspectionTaskInstance>()
                .eq(InspectionTaskInstance::getTaskInsId, flowInstanceId).last("limit 1"));
    }

    /**
     * 校验协议关键字段，并返回用于重复过滤的 event_id。
     */
    private String validateAndResolveEventId(AlertEnvelope envelope)
    {
        if (envelope == null)
        {
            throw new DetectionAlertBadRequestException("请求体不能为空");
        }
        if (!SUPPORTED_SCHEMA.equals(envelope.getSchema()))
        {
            throw new DetectionAlertBadRequestException("schema必须为" + SUPPORTED_SCHEMA);
        }
        if (envelope.getPayload() == null)
        {
            throw new DetectionAlertBadRequestException("payload不能为空");
        }

        String eventId = trimToNull(envelope.getPayload().getEventId());
        if (eventId == null)
        {
            throw new DetectionAlertBadRequestException("payload.event_id不能为空");
        }
        if (eventId.length() > MAX_EVENT_ID_LENGTH)
        {
            throw new DetectionAlertBadRequestException("payload.event_id长度不能超过" + MAX_EVENT_ID_LENGTH);
        }

        validateImage(envelope.getPayload().getImage());
        return eventId;
    }

    private void validateImage(AlertImage image)
    {
        if (image == null)
        {
            return;
        }
        if (!IMAGE_ENCODING_BASE64.equalsIgnoreCase(trimToEmpty(image.getEncoding())))
        {
            throw new DetectionAlertBadRequestException("payload.image.encoding必须为base64");
        }
        if (StringUtils.isBlank(image.getData()))
        {
            throw new DetectionAlertBadRequestException("payload.image.data不能为空");
        }
        if (image.getData().length() > MAX_BASE64_LENGTH)
        {
            throw new DetectionAlertBadRequestException("报警图片不能超过10MB");
        }
        String mediaType = trimToNull(image.getMediaType());
        if (mediaType == null || !mediaType.toLowerCase(Locale.ROOT).startsWith("image/"))
        {
            throw new DetectionAlertBadRequestException("payload.image.media_type必须是图片类型");
        }
    }

    private boolean exists(String eventId)
    {
        LambdaQueryWrapper<InspectionDetectionAlert> query = new LambdaQueryWrapper<>();
        query.eq(InspectionDetectionAlert::getEventId, eventId);
        return alertMapper.selectCount(query) > 0;
    }

    private InspectionDetectionAlert buildAlert(AlertEnvelope envelope, String idempotencyKey)
    {
        com.cmvr.inspection.domain.dto.alert.DetectionAlert payload = envelope.getPayload();
        InspectionDetectionAlert alert = new InspectionDetectionAlert();
        alert.setId(newId());
        alert.setEventId(trimToNull(payload.getEventId()));
        alert.setIdempotencyKey(idempotencyKey);
        alert.setSchema(envelope.getSchema());
        alert.setSourceId(envelope.getSourceId());
        alert.setGrpcIp(envelope.getGrpcIp());
        alert.setSequence(envelope.getSequence());
        alert.setCapturedAtNs(envelope.getCapturedAtNs());
        alert.setReceivedAtNs(envelope.getReceivedAtNs());
        alert.setTraceId(envelope.getTraceId());
        alert.setSessionId(envelope.getSessionId());
        alert.setInputPort(envelope.getInputPort());
        alert.setRuleId(payload.getRuleId());
        alert.setModelId(payload.getModelId());
        alert.setModelName(payload.getModelName());
        alert.setLabelsJson(writeJson(payload.getLabels(), "序列化labels失败"));
        alert.setScope(payload.getScope());
        alert.setScopeId(payload.getScopeId());
        alert.setHitCount(payload.getHitCount());
        alert.setWindowMs(payload.getWindowMs());
        alert.setFirstSeenNs(payload.getFirstSeenNs());
        alert.setLastSeenNs(payload.getLastSeenNs());
        alert.setTriggeredAtNs(payload.getTriggeredAtNs());
        alert.setMaxConfidence(payload.getMaxConfidence());
        alert.setRawJson(buildSanitizedRawJson(envelope));
        alert.setCreatedAt(new Date());
        return alert;
    }

    /**
     * raw_json保留协议元数据，但明确移除Base64图片，避免图片以另一种形式进入数据库。
     */
    private String buildSanitizedRawJson(AlertEnvelope envelope)
    {
        AlertImage image = envelope.getPayload().getImage();
        String imageData = image == null ? null : image.getData();
        try
        {
            // 避免构建JSON树时复制一份大Base64字符串；finally中恢复仅供随后上传MinIO。
            if (image != null)
            {
                image.setData(null);
            }
            return objectMapper.writeValueAsString(envelope);
        }
        catch (Exception ex)
        {
            throw new DetectionAlertTemporaryException("序列化报警原始数据失败", ex);
        }
        finally
        {
            if (image != null)
            {
                image.setData(imageData);
            }
        }
    }

    private String writeJson(Object value, String errorMessage)
    {
        if (value == null)
        {
            return null;
        }
        try
        {
            return objectMapper.writeValueAsString(value);
        }
        catch (Exception ex)
        {
            throw new DetectionAlertTemporaryException(errorMessage, ex);
        }
    }

    private StoredImage uploadImage(String alertId, AlertImage image)
    {
        final byte[] imageBytes;
        try
        {
            imageBytes = Base64.getDecoder().decode(image.getData().getBytes(StandardCharsets.US_ASCII));
        }
        catch (IllegalArgumentException ex)
        {
            throw new DetectionAlertBadRequestException("payload.image.data不是有效的Base64", ex);
        }
        if (imageBytes.length > MAX_IMAGE_BYTES)
        {
            throw new DetectionAlertBadRequestException("报警图片不能超过10MB");
        }

        String extension = extensionFor(image.getMediaType());
        String datePath = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        String objectName = IMAGE_OBJECT_PREFIX + "/" + datePath + "/" + alertId + extension;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes))
        {
            minioService.uploadStream(minioProperties.getBucketName(), objectName, inputStream,
                    imageBytes.length, image.getMediaType());
            return new StoredImage(objectName, buildMinioUrl(objectName));
        }
        catch (DetectionAlertBadRequestException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new DetectionAlertTemporaryException("上传报警图片到MinIO失败", ex);
        }
    }

    private String buildMinioUrl(String objectName)
    {
        String baseUrl = StringUtils.removeEnd(minioProperties.getUrl(), "/");
        return baseUrl + "/" + minioProperties.getBucketName() + "/" + objectName;
    }

    private void deleteUploadedImageQuietly(String objectName)
    {
        try
        {
            minioService.deleteFile(minioProperties.getBucketName(), objectName);
        }
        catch (Exception cleanupEx)
        {
            log.error("回滚PPE报警时删除MinIO对象失败，objectName={}", objectName, cleanupEx);
        }
    }

    private String extensionFor(String mediaType)
    {
        String normalized = trimToEmpty(mediaType).toLowerCase(Locale.ROOT);
        if ("image/jpeg".equals(normalized) || "image/jpg".equals(normalized))
        {
            return ".jpg";
        }
        if ("image/png".equals(normalized))
        {
            return ".png";
        }
        if ("image/webp".equals(normalized))
        {
            return ".webp";
        }
        // 未知图片类型使用无执行语义的后缀，实际Content-Type仍按协议上传。
        return ".img";
    }

    private String trimToNull(String value)
    {
        return StringUtils.trimToNull(value);
    }

    private String trimToEmpty(String value)
    {
        return StringUtils.trimToEmpty(value);
    }

    private String newId()
    {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private static final class StoredImage
    {
        private final String objectName;
        private final String url;

        private StoredImage(String objectName, String url)
        {
            this.objectName = objectName;
            this.url = url;
        }
    }
}
