package com.qaup.collision.rule.service;

import com.qaup.collision.common.model.MovingObject.MovingObjectType;
import com.qaup.collision.common.model.spatial.VehicleLocation;
import com.qaup.collision.rule.event.RuleViolationEvent;
import com.qaup.collision.rule.model.entity.SpatialRule;
import com.qaup.collision.rule.model.enums.RuleAlertLevel;
import com.qaup.collision.rule.model.enums.ViolationType;

import org.locationtech.jts.geom.Point;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 实时违规检测服务接口
 * 负责实时检测车辆位置的规则违规情况，生成违规事件和处理响应
 * 
 * @author AI Assistant
 * @version 1.0
 * @since 2025-01-17
 */
public interface RealTimeViolationDetector {

    // ========== 核心违规检测方法 ==========

    /**
     * 实时检测车辆位置的违规情况
     * @param vehicleLocation 车辆位置信息
     * @return 检测到的违规事件列表
     */
    List<RuleViolationEvent> detectViolations(VehicleLocation vehicleLocation);

    /**
     * 批量检测车辆位置的违规情况
     * @param vehicleLocations 车辆位置信息列表
     * @return 检测到的违规事件列表
     */
    List<RuleViolationEvent> detectBatchViolations(List<VehicleLocation> vehicleLocations);

    /**
     * 针对特定规则检测违规
     * @param vehicleLocation 车辆位置信息
     * @param rule 要检测的规则
     * @return 违规事件，如果没有违规返回null
     */
    RuleViolationEvent detectRuleViolation(VehicleLocation vehicleLocation, SpatialRule rule);

    /**
     * 检测指定位置和车辆类型的违规
     * @param vehicleId 车辆ID
     * @param vehicleType 车辆类型
     * @param location 位置
     * @param vehicleState 车辆状态参数
     * @param timestamp 时间戳
     * @return 检测到的违规事件列表
     */
    List<RuleViolationEvent> detectLocationViolations(String vehicleId, MovingObjectType vehicleType,
                                                      Point location, Map<String, Object> vehicleState, 
                                                      LocalDateTime timestamp);

    // ========== 违规事件处理方法 ==========

    /**
     * 处理检测到的违规事件
     * @param violationEvent 违规事件
     */
    void processViolationEvent(RuleViolationEvent violationEvent);

    /**
     * 批量处理违规事件
     * @param violationEvents 违规事件列表
     */
    void processBatchViolationEvents(List<RuleViolationEvent> violationEvents);

    /**
     * 处理高严重性违规事件（需要立即响应）
     * @param violationEvent 高严重性违规事件
     */
    void processCriticalViolation(RuleViolationEvent violationEvent);

    // ========== 违规严重程度评估 ==========

    /**
     * 评估违规事件的严重程度
     * @param violationEvent 违规事件
     * @return 严重程度评分（1-10，数值越高越严重）
     */
    int assessViolationSeverity(RuleViolationEvent violationEvent);

    /**
     * 根据违规类型和规则确定告警级别
     * @param violationType 违规类型
     * @param rule 相关规则
     * @param vehicleState 车辆状态
     * @return 推荐的告警级别
     */
    RuleAlertLevel determineAlertLevel(ViolationType violationType, SpatialRule rule, 
                                          Map<String, Object> vehicleState);

    /**
     * 检查是否为重复违规
     * @param vehicleId 车辆ID
     * @param ruleId 规则ID
     * @param violationType 违规类型
     * @param timeWindow 时间窗口（分钟）
     * @return 如果是重复违规返回true
     */
    boolean isDuplicateViolation(Long vehicleId, String ruleId, ViolationType violationType, int timeWindow);

    // ========== 违规响应和通知 ==========

    /**
     * 发送违规告警通知
     * @param violationEvent 违规事件
     */
    void sendViolationAlert(RuleViolationEvent violationEvent);

    /**
     * 执行违规响应动作
     * @param violationEvent 违规事件
     * @param responseActions 响应动作配置
     */
    void executeViolationResponse(RuleViolationEvent violationEvent, Map<String, Object> responseActions);

    /**
     * 记录违规处理历史
     * @param violationEvent 违规事件
     * @param processingResult 处理结果
     * @param responseTime 响应时间（毫秒）
     */
    void recordViolationProcessingHistory(RuleViolationEvent violationEvent, String processingResult, 
                                        long responseTime);

    // ========== 违规统计和分析 ==========

    /**
     * 获取车辆的违规统计信息
     * @param vehicleId 车辆ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 违规统计信息
     */
    Map<String, Object> getVehicleViolationStatistics(Long vehicleId, LocalDateTime startTime, 
                                                      LocalDateTime endTime);

    /**
     * 获取规则的违规统计信息
     * @param ruleId 规则ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 违规统计信息
     */
        Map<String, Object> getRuleViolationStatistics(String ruleId, LocalDateTime startTime, 
                                                   LocalDateTime endTime);

    /**
     * 获取实时违规热点分析
     * @param timeWindow 时间窗口（分钟）
     * @return 违规热点信息列表
     */
    List<Map<String, Object>> getViolationHotspots(int timeWindow);

    /**
     * 获取违规趋势分析
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param granularity 时间粒度（HOUR, DAY, WEEK）
     * @return 违规趋势数据
     */
    List<Map<String, Object>> getViolationTrends(LocalDateTime startTime, LocalDateTime endTime, 
                                                 String granularity);

    // ========== 检测配置和优化 ==========

    /**
     * 设置违规检测配置
     * @param config 检测配置参数
     */
    void configureViolationDetection(Map<String, Object> config);

    /**
     * 获取违规检测性能指标
     * @return 性能指标信息
     */
    Map<String, Object> getDetectionMetrics();

    /**
     * 启用/禁用实时违规检测
     * @param enabled 是否启用
     */
    void setRealTimeDetectionEnabled(boolean enabled);

    /**
     * 检查实时违规检测是否启用
     * @return 如果启用返回true
     */
    boolean isRealTimeDetectionEnabled();

    // ========== 违规检测上下文 ==========

    /**
     * 违规检测上下文类
     */
    class ViolationDetectionContext {
        private final VehicleLocation vehicleLocation;
        private final List<SpatialRule> applicableRules;
        private final Map<String, Object> detectionConfig;
        private final LocalDateTime detectionTime;
        private final String detectionId;

        public ViolationDetectionContext(VehicleLocation vehicleLocation, List<SpatialRule> applicableRules,
                                       Map<String, Object> detectionConfig, LocalDateTime detectionTime,
                                       String detectionId) {
            this.vehicleLocation = vehicleLocation;
            this.applicableRules = applicableRules;
            this.detectionConfig = detectionConfig;
            this.detectionTime = detectionTime;
            this.detectionId = detectionId;
        }

        // Getters
        public VehicleLocation getVehicleLocation() { return vehicleLocation; }
        public List<SpatialRule> getApplicableRules() { return applicableRules; }
        public Map<String, Object> getDetectionConfig() { return detectionConfig; }
        public LocalDateTime getDetectionTime() { return detectionTime; }
        public String getDetectionId() { return detectionId; }

        /**
         * 获取检测摘要信息
         */
        public String getDetectionSummary() {
            return String.format("Detection[%s]: Vehicle=%s, Rules=%d, Time=%s",
                    detectionId, vehicleLocation.getVehicleId(), 
                    applicableRules.size(), detectionTime);
        }
    }

    /**
     * 违规处理结果类
     */
    class ViolationProcessingResult {
        private final RuleViolationEvent violationEvent;
        private final boolean processed;
        private final String processingStatus;
        private final String message;
        private final long processingTimeMs;
        private final Map<String, Object> processingDetails;

        public ViolationProcessingResult(RuleViolationEvent violationEvent, boolean processed,
                                       String processingStatus, String message, long processingTimeMs,
                                       Map<String, Object> processingDetails) {
            this.violationEvent = violationEvent;
            this.processed = processed;
            this.processingStatus = processingStatus;
            this.message = message;
            this.processingTimeMs = processingTimeMs;
            this.processingDetails = processingDetails;
        }

        // Getters
        public RuleViolationEvent getViolationEvent() { return violationEvent; }
        public boolean isProcessed() { return processed; }
        public String getProcessingStatus() { return processingStatus; }
        public String getMessage() { return message; }
        public long getProcessingTimeMs() { return processingTimeMs; }
        public Map<String, Object> getProcessingDetails() { return processingDetails; }

        /**
         * 检查处理是否成功
         */
        public boolean isSuccessful() {
            return processed && "SUCCESS".equals(processingStatus);
        }

        /**
         * 获取处理结果摘要
         */
        public String getProcessingSummary() {
            return String.format("Processing[%s]: %s - %s (%dms)",
                    violationEvent.getId(), processingStatus, message, processingTimeMs);
        }
    }
} 