"""
People counting use case implementation.

This module provides a clean implementation of people counting functionality
with zone-based analysis, tracking, and alerting capabilities.
"""

from typing import Any, Dict, List, Optional, Set
from dataclasses import asdict
import time
from datetime import datetime, timezone

from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
from ..core.config import PeopleCountingConfig, ZoneConfig, AlertConfig
from ..utils import (
    filter_by_confidence,
    filter_by_categories,
    apply_category_mapping,
    count_objects_by_category,
    count_objects_in_zones,
    calculate_counting_summary,
    match_results_structure,
    bbox_smoothing,
    BBoxSmoothingConfig,
    BBoxSmoothingTracker,
    calculate_iou
)
from ..utils.geometry_utils import get_bbox_center, point_in_polygon, get_bbox_bottom25_center


class PeopleCountingUseCase(BaseProcessor):
    """People counting use case with zone analysis and alerting."""
    
    def __init__(self):
        """Initialize people counting use case."""
        super().__init__("people_counting")
        self.category = "general"
        self.CASE_TYPE: Optional[str] = 'People_Counting'
        self.CASE_VERSION: Optional[str] = '1.3'
        
        # Track ID storage for total count calculation
        self._total_track_ids = set()  # Store all unique track IDs seen across calls
        self._current_frame_track_ids = set()  # Store track IDs from current frame
        self._total_count = 0  # Cached total count
        self._last_update_time = time.time()  # Track when last updated
        
        # Zone-based tracking storage
        self._zone_current_track_ids = {}  # zone_name -> set of current track IDs in zone
        self._zone_total_track_ids = {}  # zone_name -> set of all track IDs that have been in zone
        self._zone_current_counts = {}  # zone_name -> current count in zone
        self._zone_total_counts = {}  # zone_name -> total count that have been in zone
        
        # Frame counter for tracking total frames processed
        self._total_frame_counter = 0  # Total frames processed across all calls
        
        # Global frame offset for video chunk processing
        self._global_frame_offset = 0  # Offset to add to local frame IDs for global frame numbering
        self._frames_in_current_chunk = 0  # Number of frames in current chunk
        
        # Initialize smoothing tracker
        self.smoothing_tracker = None

        # Track start time for "TOTAL SINCE" calculation
        self._tracking_start_time = None

        # --------------------------------------------------------------------- #
        # Tracking aliasing structures to merge fragmented IDs                   #
        # --------------------------------------------------------------------- #
        # Maps raw tracker IDs generated by ByteTrack to a stable canonical ID
        # that represents a real-world person. This helps avoid double counting
        # when the tracker loses a target temporarily and assigns a new ID.
        self._track_aliases: Dict[Any, Any] = {}

        # Stores metadata about each canonical track such as its last seen
        # bounding box, last update timestamp and all raw IDs that have been
        # merged into it.
        self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}

        # IoU threshold above which two bounding boxes are considered to belong
        # to the same person (empirically chosen; adjust in production if
        # needed).
        self._track_merge_iou_threshold: float = 0.04

        # Only merge with canonical tracks that were updated within this time
        # window (in seconds). This prevents accidentally merging tracks that
        # left the scene long ago.
        self._track_merge_time_window: float = 10.0

        self._ascending_alert_list: List[int] = []
        self.current_incident_end_timestamp: str = "N/A"

        self.start_timer = None


    def process(self, data: Any, config: ConfigProtocol, 
                context: Optional[ProcessingContext] = None, stream_info: Optional[Any] = None) -> ProcessingResult:
        """
        Process people counting use case - automatically detects single or multi-frame structure.
        
        Args:
            data: Raw model output (detection or tracking format)
            config: People counting configuration
            context: Processing context
            stream_info: Stream information containing frame details (optional)
            
        Returns:
            ProcessingResult: Processing result with standardized agg_summary structure
        """
        start_time = time.time()
        
        try:
            # Ensure we have the right config type
            if not isinstance(config, PeopleCountingConfig):
                return self.create_error_result(
                    "Invalid configuration type for people counting",
                    usecase=self.name,
                    category=self.category,
                    context=context
                )
            
            # Initialize processing context if not provided
            if context is None:
                context = ProcessingContext()
            
            # Detect input format and frame structure
            input_format = match_results_structure(data)
            context.input_format = input_format
            context.confidence_threshold = config.confidence_threshold
            
            is_multi_frame = self.detect_frame_structure(data)
            print("--------------------------------------")
            print("config.alert_config",config.alert_config)
            print(config)
            print("is_multi?",is_multi_frame)
            print("--------------------------------------")
            
            #self.logger.info(f"Processing people counting - Format: {input_format.value}, Multi-frame: {is_multi_frame}")
            
            # Apply smoothing if enabled
            if config.enable_smoothing and input_format == ResultFormat.OBJECT_TRACKING:
                data = self._apply_smoothing(data, config)
            
            # Process based on frame structure
            if is_multi_frame:
                
                return self._process_multi_frame(data, config, context, stream_info)
            else:
                return self._process_single_frame(data, config, context, stream_info)
                
        except Exception as e:
            self.logger.error(f"People counting failed: {str(e)}", exc_info=True)
            
            if context:
                context.mark_completed()
            
            return self.create_error_result(
                str(e), 
                type(e).__name__,
                usecase=self.name,
                category=self.category,
                context=context
            )
        
    def _process_multi_frame(self, data: Dict, config: PeopleCountingConfig, context: ProcessingContext, stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
        """Process multi-frame data to generate frame-wise agg_summary."""
        
        frame_incidents = {}
        frame_tracking_stats = {}
        frame_business_analytics = {}
        frame_human_text = {}
        frame_alerts = {}
        
        # Increment total frame counter
        frames_in_this_call = len(data)
        self._total_frame_counter += frames_in_this_call
        
        # Process each frame individually
        for frame_key, frame_detections in data.items():
            # Extract frame ID from tracking data
            frame_id = self._extract_frame_id_from_tracking(frame_detections, frame_key)
            global_frame_id = self.get_global_frame_id(frame_id)
            
            # Process this single frame's detections
            alerts, incidents_list, tracking_stats_list, business_analytics_list, summary_list  = self._process_frame_detections(
                frame_detections, config, global_frame_id, stream_info
            )
            incidents = incidents_list[0] if incidents_list else {}
            tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
            business_analytics = business_analytics_list[0] if business_analytics_list else {}
            summary = summary_list[0] if summary_list else {}
            
            # Store frame-wise results
            if incidents:
                frame_incidents[global_frame_id] = incidents
            if tracking_stats:
                frame_tracking_stats[global_frame_id] = tracking_stats
            if business_analytics:
                frame_business_analytics[global_frame_id] = business_analytics
            if summary:
                frame_human_text[global_frame_id] = summary
            if alerts:
                frame_alerts[global_frame_id] = alerts
        
        # Update global frame offset after processing this chunk
        self.update_global_frame_offset(frames_in_this_call)
        
        # Create frame-wise agg_summary
        agg_summary = self.create_frame_wise_agg_summary(
            frame_incidents, frame_tracking_stats, frame_business_analytics, frame_alerts,
            frame_human_text=frame_human_text
        )
        
        # Mark processing as completed
        context.mark_completed()
        
        # Create result with standardized agg_summary
        return self.create_result(
            data={"agg_summary": agg_summary},
            usecase=self.name,
            category=self.category,
            context=context
        )

    def _process_single_frame(self, data: Any, config: PeopleCountingConfig, context: ProcessingContext, stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
        """Process single frame data and return standardized agg_summary."""
        
        current_frame = stream_info.get("input_settings", {}).get("start_frame", "current_frame")
        # Process frame data
        alerts, incidents_list, tracking_stats_list, business_analytics_list, summary_list  = self._process_frame_detections(
            data, config, current_frame, stream_info
        )
        incidents = incidents_list[0] if incidents_list else {}
        tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
        business_analytics = business_analytics_list[0] if business_analytics_list else {}
        summary = summary_list[0] if summary_list else {}
        
        # Create single-frame agg_summary
        agg_summary = self.create_agg_summary(
            current_frame, incidents, tracking_stats, business_analytics, alerts, human_text=summary
        )
        
        # Mark processing as completed
        context.mark_completed()
        
        # Create result with standardized agg_summary
        return self.create_result(
            data={"agg_summary": agg_summary},
            usecase=self.name,
            category=self.category,
            context=context
        )
    
        
    def _process_frame_detections(self, frame_data: Any, config: PeopleCountingConfig, frame_id: str, stream_info: Optional[Dict[str, Any]] = None) -> tuple:
        """Process detections from a single frame and return standardized components."""
        
        # Convert frame_data to list if it's not already
        if isinstance(frame_data, list):
            frame_detections = frame_data
        else:
            # Handle other formats as needed
            frame_detections = []
        
        # Step 1: Apply confidence filtering to this frame
        if config.confidence_threshold is not None:
            frame_detections = [d for d in frame_detections if d.get("confidence", 0) >= config.confidence_threshold]
        
        # Step 2: Apply category mapping if provided
        if config.index_to_category:
            frame_detections = apply_category_mapping(frame_detections, config.index_to_category)
        
        # Step 3: Filter to person categories
        if config.person_categories:
            frame_detections = [d for d in frame_detections if d.get("category") in config.person_categories]
        
        # Step 4: Create counting summary for this frame
        counting_summary = {
            "total_objects": len(frame_detections),
            "detections": frame_detections,
            "categories": {}
        }
        
        # Count by category
        for detection in frame_detections:
            category = detection.get("category", "unknown")
            counting_summary["categories"][category] = counting_summary["categories"].get(category, 0) + 1
        
        # Step 4.5: Always update tracking state BEFORE zone enhancements so detections have track_ids
        self._update_tracking_state(counting_summary)

        # Step 5: Zone analysis for this frame
        zone_analysis = {}
        if config.zone_config and config.zone_config.zones:
            # Convert single frame to format expected by count_objects_in_zones
            frame_data = frame_detections #[frame_detections]
            zone_analysis = count_objects_in_zones(frame_data, config.zone_config.zones)
            
            # Update zone tracking with current frame data (now detections have canonical track_ids)
            if zone_analysis and config.enable_tracking:
                enhanced_zone_analysis = self._update_zone_tracking(zone_analysis, frame_detections, config)
                # Merge enhanced zone analysis with original zone analysis
                for zone_name, enhanced_data in enhanced_zone_analysis.items():
                    zone_analysis[zone_name] = enhanced_data
        
        # Step 5: Generate insights and alerts for this frame
        alerts = self._check_alerts(counting_summary, zone_analysis, config, frame_id)
        
        # Step 6: Generate summary and standardized agg_summary components for this frame
        incidents = self._generate_incidents(counting_summary, zone_analysis, alerts, config, frame_id, stream_info)
        incidents = []
        tracking_stats = self._generate_tracking_stats(counting_summary, zone_analysis, config, frame_id=frame_id, alerts=alerts, stream_info=stream_info)
        business_analytics = self._generate_business_analytics(counting_summary, zone_analysis, config, frame_id, stream_info, is_empty=True)
        summary = self._generate_summary(counting_summary, incidents, tracking_stats, business_analytics, alerts)
        
        # Return standardized components as tuple
        return alerts, incidents, tracking_stats, business_analytics, summary
    
    def _generate_incidents(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: PeopleCountingConfig, frame_id: str, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
        """Generate standardized incidents for the agg_summary structure."""
        
        camera_info = self.get_camera_info_from_stream(stream_info)
        incidents = []
        total_people = counting_summary.get("total_objects", 0)
        current_timestamp = self._get_current_timestamp_str(stream_info, frame_id=frame_id)
        self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list

        alert_settings=[]
        if config.alert_config and hasattr(config.alert_config, 'alert_type'):
            alert_settings.append({
                "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                "incident_category": self.CASE_TYPE,
                "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
                "ascending": True,
                "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                                    getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
                            }
            })

        if total_people > 0:
            # Determine event level based on thresholds
            
            level = "info"
            intensity = 5.0
            start_timestamp = self._get_start_timestamp_str(stream_info)
            if start_timestamp and self.current_incident_end_timestamp=='N/A':
                self.current_incident_end_timestamp = 'Incident still active'
            elif start_timestamp and self.current_incident_end_timestamp=='Incident still active':
                if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5: 
                    self.current_incident_end_timestamp = current_timestamp
            elif self.current_incident_end_timestamp!='Incident still active' and self.current_incident_end_timestamp!='N/A':
                self.current_incident_end_timestamp = 'N/A'
            
            if config.alert_config and hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
                threshold = config.alert_config.count_thresholds.get("all", 10)
                intensity = min(10.0, (total_people / threshold) * 10)
                
                if intensity >= 9:
                    level = "critical"
                    self._ascending_alert_list.append(3)
                elif intensity >= 7:
                    level = "significant"
                    self._ascending_alert_list.append(2)
                elif intensity >= 5:
                    level = "medium"
                    self._ascending_alert_list.append(1)
                else:
                    level = "low"
                    self._ascending_alert_list.append(0)
            else:
                if total_people > 30:
                    level = "critical"
                    intensity = 10.0
                    self._ascending_alert_list.append(3)
                elif total_people > 25:
                    level = "significant"
                    intensity = 9.0
                    self._ascending_alert_list.append(2)
                elif total_people > 15:
                    level = "medium"
                    intensity = 7.0
                    self._ascending_alert_list.append(1)
                else:
                    level = "low"
                    intensity = min(10.0, total_people / 3.0)
                    self._ascending_alert_list.append(0)
            
             # Generate human text in new format
            human_text_lines = [f"INCIDENTS DETECTED @ {current_timestamp}:"]
            human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE,level)}")
            human_text = "\n".join(human_text_lines)

            # Main people counting incident
            event= self.create_incident(incident_id=self.CASE_TYPE+'_'+str(frame_id), incident_type=self.CASE_TYPE,
                       severity_level=level, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
                       start_time=start_timestamp, end_time=self.current_incident_end_timestamp,
                       level_settings= {"low": 1, "medium": 3, "significant":4, "critical": 7})
            incidents.append(event)
        else:
            self._ascending_alert_list.append(0)
            incidents.append({})
        
        # Add zone-specific events if applicable
        if zone_analysis:
            human_text_lines.append(f"\t- ZONE EVENTS:")
            for zone_name, zone_count in zone_analysis.items():
                zone_total = self._robust_zone_total(zone_count)
                if zone_total > 0:
                    zone_intensity = min(10.0, zone_total / 5.0)
                    zone_level = "info"
                    if intensity >= 9:
                        level = "critical"
                        self._ascending_alert_list.append(3)
                    elif intensity >= 7:
                        level = "significant"
                        self._ascending_alert_list.append(2)
                    elif intensity >= 5:
                        level = "medium"
                        self._ascending_alert_list.append(1)
                    else:
                        level = "low"
                        self._ascending_alert_list.append(0)
                    
                    if zone_total > 0:
                        human_text_lines.append(f"\t\t- Zone name: {zone_name}")
                        human_text_lines.append(f"\t\t\t- Total people in zone: {zone_total}")
                    # Main people counting incident
                    event= self.create_incident(incident_id=self.CASE_TYPE+'_'+'zone_'+zone_name+str(frame_id), incident_type=self.CASE_TYPE,
                            severity_level=zone_level, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
                            start_time=start_timestamp, end_time=self.current_incident_end_timestamp,
                            level_settings= {"low": 1, "medium": 3, "significant":4, "critical": 7})
                    incidents.append(event)
        return incidents

    def _generate_tracking_stats(self, counting_summary: Dict, zone_analysis: Dict, config: PeopleCountingConfig, frame_id: str, alerts: Any=[], stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
        """Generate tracking stats using standardized methods."""
        
        total_people = counting_summary.get("total_objects", 0)
        
        # Get total count from cached tracking state
        total_unique_count = self.get_total_count()
        current_frame_count = self.get_current_frame_count()
        
        # Get camera info using standardized method
        camera_info = self.get_camera_info_from_stream(stream_info)
        
        # Build total_counts using standardized method
        total_counts = []
        per_category_total = {}
        
        for category in config.person_categories or ["person"]:
            # Get count for this category from zone analysis or counting summary
            category_total_count = 0
            if zone_analysis:
                for zone_data in zone_analysis.values():
                    if isinstance(zone_data, dict) and "total_count" in zone_data:
                        category_total_count += zone_data.get("total_count", 0)
                    elif isinstance(zone_data, dict):
                        # Sum up zone counts
                        for v in zone_data.values():
                            if isinstance(v, int):
                                category_total_count += v
                            elif isinstance(v, list):
                                category_total_count += len(v)
                    elif isinstance(zone_data, (int, list)):
                        category_total_count += len(zone_data) if isinstance(zone_data, list) else zone_data
            else:
                # Use total unique count from tracking state
                category_total_count = total_unique_count
            
            if category_total_count > 0:
                total_counts.append(self.create_count_object(category, category_total_count))
                per_category_total[category] = category_total_count
        
        # Build current_counts using standardized method
        current_counts = []
        per_category_current = {}
        
        for category in config.person_categories or ["person"]:
            # Get current count for this category
            category_current_count = 0
            if zone_analysis:
                for zone_data in zone_analysis.values():
                    if isinstance(zone_data, dict) and "current_count" in zone_data:
                        category_current_count += zone_data.get("current_count", 0)
                    elif isinstance(zone_data, dict):
                        # For current frame, look at detections count
                        for v in zone_data.values():
                            if isinstance(v, int):
                                category_current_count += v
                            elif isinstance(v, list):
                                category_current_count += len(v)
                    elif isinstance(zone_data, (int, list)):
                        category_current_count += len(zone_data) if isinstance(zone_data, list) else zone_data
            else:
                # Count detections in current frame for this category
                detections = counting_summary.get("detections", [])
                category_current_count = sum(1 for d in detections if d.get("category") == category)
        
            if category_current_count > 0 or total_people > 0:  # Include even if 0 when there are people
                current_counts.append(self.create_count_object(category, category_current_count))
                per_category_current[category] = category_current_count
        
        # Prepare detections using standardized method (without confidence and track_id)
        detections = []
        for detection in counting_summary.get("detections", []):
            bbox = detection.get("bounding_box", {})
            category = detection.get("category", "person")
            # Include segmentation if available (like in eg.json)
            if detection.get("masks"):
                segmentation= detection.get("masks", [])
                detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
            elif detection.get("segmentation"):
                segmentation= detection.get("segmentation")
                detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
            elif detection.get("mask"):
                segmentation= detection.get("mask")
                detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
            else:
                detection_obj = self.create_detection_object(category, bbox)
            detections.append(detection_obj)
        
        # Build alerts and alert_settings arrays
        alert_settings = []
        if config.alert_config and hasattr(config.alert_config, 'alert_type'):
            alert_settings.append({
                "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                "incident_category": self.CASE_TYPE,
                "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
                "ascending": True,
                "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                                    getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
                            }
            })
        if zone_analysis:
                human_text_lines=[]
                current_timestamp = self._get_current_timestamp_str(stream_info, frame_id=frame_id)
                start_timestamp = self._get_start_timestamp_str(stream_info)
                human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
                def robust_zone_total(zone_count):
                    if isinstance(zone_count, dict):
                        total = 0
                        for v in zone_count.values():
                            if isinstance(v, int):
                                total += v
                            elif isinstance(v, list) and total==0:
                                total += len(v)
                        return total
                    elif isinstance(zone_count, list):
                        return len(zone_count)
                    elif isinstance(zone_count, int):
                        return zone_count
                    else:
                        return 0
                human_text_lines.append(f"\t- People Detected: {total_people}")
                human_text_lines.append("")
                human_text_lines.append(f"TOTAL SINCE @ {start_timestamp}:")
                
                for zone_name, zone_count in zone_analysis.items():
                        zone_total = robust_zone_total(zone_count)
                        human_text_lines.append(f"\t- Zone name: {zone_name}")
                        human_text_lines.append(f"\t\t- Total count in zone: {zone_total-1}")

                if total_unique_count > 0:
                    human_text_lines.append(f"\t- Total unique people in the scene: {total_unique_count}")
                if alerts:
                    for alert in alerts:
                        human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
                else:
                    human_text_lines.append("Alerts: None")
                human_text = "\n".join(human_text_lines)  
        else:      
            human_text = self._generate_human_text_for_tracking(total_people, total_unique_count, config, frame_id, alerts, stream_info)
        
         # Create high precision timestamps for input_timestamp and reset_timestamp
        high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True, frame_id=frame_id)
        high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
        # Create tracking_stat using standardized method
        tracking_stat = self.create_tracking_stats(
            total_counts, current_counts, detections, human_text, camera_info, alerts, alert_settings, start_time=high_precision_start_timestamp, reset_time=high_precision_reset_timestamp
        )
        
        return [tracking_stat]
    
    def _generate_human_text_for_tracking(self, total_people: int, total_unique_count: int, config: PeopleCountingConfig, frame_id: str, alerts:Any=[], stream_info: Optional[Dict[str, Any]] = None) -> str:
        """Generate human-readable text for tracking stats in old format."""
        from datetime import datetime, timezone
        
        human_text_lines=[]
        current_timestamp = self._get_current_timestamp_str(stream_info, precision=True, frame_id=frame_id)
        start_timestamp = self._get_start_timestamp_str(stream_info, precision=True)

        human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
        human_text_lines.append(f"\t- People Detected: {total_people}")

        human_text_lines.append("")
        if total_unique_count > 0:
            human_text_lines.append(f"TOTAL SINCE @ {start_timestamp}:")
            human_text_lines.append(f"\t- Total unique people count: {total_unique_count}")

        if alerts:
            for alert in alerts:
                human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
        else:
            human_text_lines.append("Alerts: None")
        
        return "\n".join(human_text_lines)

    def _check_alerts(self, counting_summary: Dict, zone_analysis: Dict, 
                     config: PeopleCountingConfig, frame_id: str) -> List[Dict]:
        """Check for alert conditions and generate alerts."""
        def get_trend(data, lookback=900, threshold=0.6):
            '''
            Determine if the trend is ascending or descending based on actual value progression.
            Now works with values 0,1,2,3 (not just binary).
            '''
            window = data[-lookback:] if len(data) >= lookback else data
            if len(window) < 2:
                return True  # not enough data to determine trend
            increasing = 0
            total = 0
            for i in range(1, len(window)):
                if window[i] >= window[i - 1]:
                    increasing += 1
                total += 1
            ratio = increasing / total
            if ratio >= threshold:
                return True
            elif ratio <= (1 - threshold):
                return False
        alerts = []
        
        if not config.alert_config:
            return alerts
        
        total_people = counting_summary.get("total_objects", 0)
        
        # Count threshold alerts
        if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:

            for category, threshold in config.alert_config.count_thresholds.items():
                if category == "all" and total_people >= threshold:

                    alerts.append({
                        "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                        "alert_id": "alert_"+category+'_'+frame_id,
                        "incident_category": self.CASE_TYPE,
                        "threshold_level": threshold,
                        "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
                        "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                                     getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
                                    }                    
                    })
                elif category in counting_summary.get("by_category", {}):
                    count = counting_summary["by_category"][category]

                    if count >= threshold:
                        alerts.append({
                        "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                        "alert_id": "alert_"+category+'_'+frame_id,
                        "incident_category": self.CASE_TYPE,
                        "threshold_level": threshold,
                        "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
                        "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                                     getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
                                    }                    
                    })
        else: 
            pass
        
        # Zone occupancy threshold alerts
        if hasattr(config.alert_config, 'occupancy_thresholds') and config.alert_config.occupancy_thresholds:
            for zone_name, threshold in config.alert_config.occupancy_thresholds.items():
                if zone_name in zone_analysis:
                    # Calculate zone_count robustly (supports int, list, dict values)
                    print('ZONEEE',zone_name, zone_analysis[zone_name])
                    zone_count = self._robust_zone_total(zone_analysis[zone_name])
                    if zone_count >= threshold:
                        alerts.append({
                        "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                        "alert_id": f"alert_zone_{zone_name}_{frame_id}",
                        "incident_category": f"{self.CASE_TYPE}_{zone_name}",
                        "threshold_level": threshold,
                        "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
                        "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
                                     getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
                                    }                    
                    })
        
        return alerts

    def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, config: PeopleCountingConfig, frame_id: str, stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
        """Generate standardized business analytics for the agg_summary structure."""
        if is_empty:
            return []
        business_analytics = []

        total_people = counting_summary.get("total_objects", 0)
        
        # Get camera info using standardized method
        camera_info = self.get_camera_info_from_stream(stream_info)
        
        if total_people > 0 or config.enable_analytics:
            # Calculate analytics statistics
            analytics_stats = {
                "people_count": total_people,
                "unique_people_count": self.get_total_count(),
                "current_frame_count": self.get_current_frame_count()
            }
            
            # Add zone analytics if available
            if zone_analysis:
                zone_stats = {}
                for zone_name, zone_count in zone_analysis.items():
                    zone_total = self._robust_zone_total(zone_count)
                    zone_stats[f"{zone_name}_occupancy"] = zone_total
                analytics_stats.update(zone_stats)
            
            # Generate human text for analytics
            current_timestamp = self._get_current_timestamp_str(stream_info, frame_id=frame_id)
            start_timestamp = self._get_start_timestamp_str(stream_info)
            
            analytics_human_text = self.generate_analytics_human_text(
                "people_counting_analytics", analytics_stats, current_timestamp, start_timestamp
            )
            
            # Create business analytics using standardized method
            analytics = self.create_business_analytics(
                "people_counting_analytics", analytics_stats, analytics_human_text, camera_info
            )
            business_analytics.append(analytics)
        
        return business_analytics

    def _generate_summary(self, summary: dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
        """
        Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
        """
        lines = []
        lines.append("Application Name: "+self.CASE_TYPE)
        lines.append("Application Version: "+self.CASE_VERSION)
        if len(incidents) > 0:
            lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
        if len(tracking_stats) > 0:
            lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
        if len(business_analytics) > 0:
            lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")

        if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
            lines.append("Summary: "+"No Summary Data")

        return ["\n".join(lines)]
                
    def _calculate_metrics(self, counting_summary: Dict, zone_analysis: Dict, 
                          config: PeopleCountingConfig, context: ProcessingContext) -> Dict[str, Any]:
        """Calculate detailed metrics for analytics."""
        total_people = counting_summary.get("total_objects", 0)
        
        metrics = {
            "total_people": total_people,
            "processing_time": context.processing_time or 0.0,
            "input_format": context.input_format.value,
            "confidence_threshold": config.confidence_threshold,
            "zones_analyzed": len(zone_analysis),
            "detection_rate": 0.0,
            "coverage_percentage": 0.0
        }
        
        # Calculate detection rate
        if config.time_window_minutes and config.time_window_minutes > 0:
            metrics["detection_rate"] = (total_people / config.time_window_minutes) * 60
        
        # Calculate zone coverage
        if zone_analysis and total_people > 0:
            people_in_zones = 0
            for zone_counts in zone_analysis.values():
                if isinstance(zone_counts, dict):
                    for v in zone_counts.values():
                        if isinstance(v, int):
                            people_in_zones += v
                        elif isinstance(v, list):
                            people_in_zones += len(v)
                elif isinstance(zone_counts, list):
                    people_in_zones += len(zone_counts)
                elif isinstance(zone_counts, int):
                    people_in_zones += zone_counts
            metrics["coverage_percentage"] = (people_in_zones / total_people) * 100
        
        # Unique tracking metrics
        if config.enable_unique_counting:
            unique_count = self._count_unique_tracks(counting_summary, config)
            if unique_count is not None:
                metrics["unique_people"] = unique_count
                metrics["tracking_efficiency"] = (unique_count / total_people) * 100 if total_people > 0 else 0
        
        # Per-zone metrics
        if zone_analysis:
            zone_metrics = {}
            for zone_name, zone_counts in zone_analysis.items():
                # Robustly sum counts, handling dicts with int or list values
                if isinstance(zone_counts, dict):
                    zone_total = 0
                    for v in zone_counts.values():
                        if isinstance(v, int):
                            zone_total += v
                        elif isinstance(v, list):
                            zone_total += len(v)
                elif isinstance(zone_counts, list):
                    zone_total = len(zone_counts)
                elif isinstance(zone_counts, int):
                    zone_total = zone_counts
                else:
                    zone_total = 0
                zone_metrics[zone_name] = {
                    "count": zone_total,
                    "percentage": (zone_total / total_people) * 100 if total_people > 0 else 0
                }
            metrics["zone_metrics"] = zone_metrics
        
        return metrics
    
    def _extract_predictions(self, data: Any) -> List[Dict[str, Any]]:
        """Extract predictions from processed data for API compatibility."""
        predictions = []
        
        try:
            if isinstance(data, list):
                # Detection format
                for item in data:
                    prediction = self._normalize_prediction(item)
                    if prediction:
                        predictions.append(prediction)
            
            elif isinstance(data, dict):
                # Frame-based or tracking format
                for frame_id, items in data.items():
                    if isinstance(items, list):
                        for item in items:
                            prediction = self._normalize_prediction(item)
                            if prediction:
                                prediction["frame_id"] = frame_id
                                predictions.append(prediction)
        
        except Exception as e:
            self.logger.warning(f"Failed to extract predictions: {str(e)}")
        
        return predictions
    
    def _normalize_prediction(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """Normalize a single prediction item."""
        if not isinstance(item, dict):
            return {}
        
        return {
            "category": item.get("category", item.get("class", "unknown")),
            "confidence": item.get("confidence", item.get("score", 0.0)),
            "bounding_box": item.get("bounding_box", item.get("bbox", {})),
            "track_id": item.get("track_id")
        }
    
    def _get_detections_with_confidence(self, counting_summary: Dict) -> List[Dict]:
        """Extract detection items with confidence scores."""
        return counting_summary.get("detections", [])
    
    def _count_unique_tracks(self, counting_summary: Dict, config: PeopleCountingConfig = None) -> Optional[int]:
        """Count unique tracks if tracking is enabled."""
        # Always update tracking state regardless of enable_unique_counting setting
        self._update_tracking_state(counting_summary)
        
        # Only return the count if unique counting is enabled
        if config and config.enable_unique_counting:
            return self._total_count if self._total_count > 0 else None
        else:
            return None
    
    def _update_tracking_state(self, counting_summary: Dict) -> None:
        """Update tracking state with current frame data (always called)."""
        detections = self._get_detections_with_confidence(counting_summary)

        if not detections:
            return

        # Map raw tracker IDs to canonical IDs to avoid duplicate counting
        current_frame_tracks: Set[Any] = set()

        # Local sequence to make ephemeral IDs unique within the same call
        ephemeral_seq = 0

        for detection in detections:
            # Prefer explicit tracker-provided ID when available
            raw_track_id = detection.get("track_id")

            # Always require a bbox to perform IoU-based merging
            bbox = detection.get("bounding_box", detection.get("bbox"))
            if not bbox:
                continue

            # For single-frame detectors (e.g., plain YOLO) there is no track_id.
            # Generate a short-lived ID and merge by IoU against recent canonical tracks.
            if raw_track_id is None:
                raw_track_id = self._generate_ephemeral_track_id(bbox, ephemeral_seq)
                ephemeral_seq += 1

            canonical_id = self._merge_or_register_track(raw_track_id, bbox)

            # Propagate canonical ID so that downstream logic (including zone
            # tracking and event generation) operates on the de-duplicated ID.
            detection["track_id"] = canonical_id
            current_frame_tracks.add(canonical_id)

        # Update total track IDs with new canonical IDs from current frame
        old_total_count = len(self._total_track_ids)
        self._total_track_ids.update(current_frame_tracks)
        self._current_frame_track_ids = current_frame_tracks

        # Update total count
        self._total_count = len(self._total_track_ids)
        self._last_update_time = time.time()

        # Log tracking state updates
        if len(current_frame_tracks) > 0:
            new_tracks = current_frame_tracks - (self._total_track_ids - current_frame_tracks)
            if new_tracks:
                self.logger.debug(
                    f"Tracking state updated: {len(new_tracks)} new canonical track IDs added, total unique tracks: {self._total_count}")
            else:
                self.logger.debug(
                    f"Tracking state updated: {len(current_frame_tracks)} current frame canonical tracks, total unique tracks: {self._total_count}")

    def _generate_ephemeral_track_id(self, bbox: Any, seq: int) -> str:
        """Create a short-lived raw track id for detections without a track_id.

        Combines a coarse hash of the bbox geometry with a per-call sequence and
        a millisecond timestamp, so the same person across adjacent frames will
        still be merged to the same canonical track via IoU and time window,
        while avoiding long-lived ID collisions across distant calls.
        """
        try:
            # Normalize bbox to xyxy list for hashing
            if isinstance(bbox, dict):
                if "x1" in bbox:
                    xyxy = [bbox.get("x1"), bbox.get("y1"), bbox.get("x2"), bbox.get("y2")]
                elif "xmin" in bbox:
                    xyxy = [bbox.get("xmin"), bbox.get("ymin"), bbox.get("xmax"), bbox.get("ymax")]
                else:
                    values = list(bbox.values())
                    xyxy = values[:4] if len(values) >= 4 else []
            elif isinstance(bbox, list):
                xyxy = bbox[:4]
            else:
                xyxy = []

            if len(xyxy) < 4:
                xyxy = [0, 0, 0, 0]

            x1, y1, x2, y2 = xyxy
            # Coarse-quantize geometry to stabilize hash across minor jitter
            cx = int(round((float(x1) + float(x2)) / 2.0))
            cy = int(round((float(y1) + float(y2)) / 2.0))
            w = int(round(abs(float(x2) - float(x1))))
            h = int(round(abs(float(y2) - float(y1))))
            geom_token = f"{cx}_{cy}_{w}_{h}"
        except Exception:
            geom_token = "0_0_0_0"

        ms = int(time.time() * 1000)
        return f"tmp_{ms}_{seq}_{abs(hash(geom_token)) % 1000003}"
    
    def get_total_count(self) -> int:
        """Get the total count of unique people tracked across all calls."""
        return self._total_count
    
    def get_current_frame_count(self) -> int:
        """Get the count of people in the current frame."""
        return len(self._current_frame_track_ids)
    
    def get_total_frames_processed(self) -> int:
        """Get the total number of frames processed across all calls."""
        return self._total_frame_counter
    
    def set_global_frame_offset(self, offset: int) -> None:
        """Set the global frame offset for video chunk processing."""
        self._global_frame_offset = offset
        self.logger.info(f"Global frame offset set to: {offset}")
    
    def get_global_frame_offset(self) -> int:
        """Get the current global frame offset."""
        return self._global_frame_offset
    
    def update_global_frame_offset(self, frames_in_chunk: int) -> None:
        """Update global frame offset after processing a chunk."""
        old_offset = self._global_frame_offset
        self._global_frame_offset += frames_in_chunk
        self.logger.info(f"Global frame offset updated: {old_offset} -> {self._global_frame_offset} (added {frames_in_chunk} frames)")
    
    def get_global_frame_id(self, local_frame_id: str) -> str:
        """Convert local frame ID to global frame ID."""
        try:
            # Try to convert local_frame_id to integer
            local_frame_num = int(local_frame_id)
            global_frame_num = local_frame_num #+ self._global_frame_offset
            return str(global_frame_num)
        except (ValueError, TypeError):
            # If local_frame_id is not a number (e.g., timestamp), return as is
            return local_frame_id
    
    def get_track_ids_info(self) -> Dict[str, Any]:
        """Get detailed information about track IDs."""
        return {
            "total_count": self._total_count,
            "current_frame_count": len(self._current_frame_track_ids),
            "total_unique_track_ids": len(self._total_track_ids),
            "current_frame_track_ids": list(self._current_frame_track_ids),
            "last_update_time": self._last_update_time,
            "total_frames_processed": self._total_frame_counter
        }
    
    def get_tracking_debug_info(self) -> Dict[str, Any]:
        """Get detailed debugging information about tracking state."""
        return {
            "total_track_ids": list(self._total_track_ids),
            "current_frame_track_ids": list(self._current_frame_track_ids),
            "total_count": self._total_count,
            "current_frame_count": len(self._current_frame_track_ids),
            "total_frames_processed": self._total_frame_counter,
            "last_update_time": self._last_update_time,
            "zone_current_track_ids": {zone: list(tracks) for zone, tracks in self._zone_current_track_ids.items()},
            "zone_total_track_ids": {zone: list(tracks) for zone, tracks in self._zone_total_track_ids.items()},
            "zone_current_counts": self._zone_current_counts.copy(),
            "zone_total_counts": self._zone_total_counts.copy(),
            "global_frame_offset": self._global_frame_offset,
            "frames_in_current_chunk": self._frames_in_current_chunk
        }
    
    def get_frame_info(self) -> Dict[str, Any]:
        """Get detailed information about frame processing and global frame offset."""
        return {
            "global_frame_offset": self._global_frame_offset,
            "total_frames_processed": self._total_frame_counter,
            "frames_in_current_chunk": self._frames_in_current_chunk,
            "next_global_frame": self._global_frame_offset + self._frames_in_current_chunk
        }
    
    def reset_tracking_state(self) -> None:
        """
          WARNING: This completely resets ALL tracking data including cumulative totals!
        
        This should ONLY be used when:
        - Starting a completely new tracking session
        - Switching to a different video/stream
        - Manual reset requested by user
        
        For clearing expired/stale tracks, use clear_current_frame_tracking() instead.
        """
        self._total_track_ids.clear()
        self._current_frame_track_ids.clear()
        self._total_count = 0
        self._last_update_time = time.time()
        
        # Clear zone tracking data
        self._zone_current_track_ids.clear()
        self._zone_total_track_ids.clear()
        self._zone_current_counts.clear()
        self._zone_total_counts.clear()
        
        # Reset frame counter and global frame offset
        self._total_frame_counter = 0
        self._global_frame_offset = 0
        self._frames_in_current_chunk = 0

        # Clear aliasing information
        self._canonical_tracks.clear()
        self._track_aliases.clear()
        self._tracking_start_time = None
        
        self.logger.warning(" FULL tracking state reset - all track IDs, zone data, frame counter, and global frame offset cleared. Cumulative totals lost!")
    
    def clear_current_frame_tracking(self) -> int:
        """
        MANUAL USE ONLY: Clear only current frame tracking data while preserving cumulative totals.
        
         This method is NOT called automatically anywhere in the code.
        
        This is the SAFE method to use for manual clearing of stale/expired current frame data.
        The cumulative total (self._total_count) is always preserved.
        
        In streaming scenarios, you typically don't need to call this at all.
        
        Returns:
            Number of current frame tracks cleared
        """
        old_current_count = len(self._current_frame_track_ids)
        self._current_frame_track_ids.clear()
        
        # Clear current zone tracking (but keep total zone tracking)
        cleared_zone_tracks = 0
        for zone_name in list(self._zone_current_track_ids.keys()):
            cleared_zone_tracks += len(self._zone_current_track_ids[zone_name])
            self._zone_current_track_ids[zone_name].clear()
            self._zone_current_counts[zone_name] = 0
        
        # Update timestamp
        self._last_update_time = time.time()
        
        self.logger.info(f"Cleared {old_current_count} current frame tracks and {cleared_zone_tracks} zone current tracks. Cumulative total preserved: {self._total_count}")
        return old_current_count
    
    def reset_frame_counter(self) -> None:
        """Reset only the frame counter."""
        old_count = self._total_frame_counter
        self._total_frame_counter = 0
        self.logger.info(f"Frame counter reset from {old_count} to 0")
    
    def clear_expired_tracks(self, max_age_seconds: float = 300.0) -> int:
        """
        MANUAL USE ONLY: Clear current frame tracking data if no updates for a while.
        
          This method is NOT called automatically anywhere in the code.
        It's provided as a utility function for manual cleanup if needed.
        
        In streaming scenarios, you typically don't need to call this at all.
        The cumulative total should keep growing as new unique people are detected.
        
        This method only clears current frame tracking data while preserving
        the cumulative total count. The cumulative total should never decrease.
        
        Args:
            max_age_seconds: Maximum age in seconds before clearing current frame tracks
            
        Returns:
            Number of current frame tracks cleared
        """
        current_time = time.time()
        if current_time - self._last_update_time > max_age_seconds:
            # Use the safe method that preserves cumulative totals
            cleared_count = self.clear_current_frame_tracking()
            self.logger.info(f"Manual cleanup: cleared {cleared_count} expired current frame tracks (age > {max_age_seconds}s)")
            return cleared_count
        return 0
    
    def _update_zone_tracking(self, zone_analysis: Dict[str, Dict[str, int]], detections: List[Dict], config: PeopleCountingConfig) -> Dict[str, Dict[str, Any]]:
        """
        Update zone tracking with current frame data.
        
        Args:
            zone_analysis: Current zone analysis results
            detections: List of detections with track IDs
            config: People counting configuration with zone polygons
            
        Returns:
            Enhanced zone analysis with tracking information
        """
        if not zone_analysis or not config.zone_config or not config.zone_config.zones:
            return {}
        
        enhanced_zone_analysis = {}
        zones = config.zone_config.zones
        
        # Get current frame track IDs in each zone
        current_frame_zone_tracks = {}
        
        # Initialize zone tracking for all zones
        for zone_name in zones.keys():
            current_frame_zone_tracks[zone_name] = set()
            if zone_name not in self._zone_current_track_ids:
                self._zone_current_track_ids[zone_name] = set()
            if zone_name not in self._zone_total_track_ids:
                self._zone_total_track_ids[zone_name] = set()
        
        # Check each detection against each zone
        for detection in detections:
            track_id = detection.get("track_id")
            if track_id is None:
                continue
            
            # Get detection bbox
            bbox = detection.get("bounding_box", detection.get("bbox"))
            if not bbox:
                continue
            
            # Get detection center point
            center_point = get_bbox_bottom25_center(bbox) #get_bbox_center(bbox)
            
            # Check which zone this detection is in using actual zone polygons
            for zone_name, zone_polygon in zones.items():
                # Convert polygon points to tuples for point_in_polygon function
                # zone_polygon format: [[x1, y1], [x2, y2], [x3, y3], ...]
                polygon_points = [(point[0], point[1]) for point in zone_polygon]
                
                # Check if detection center is inside the zone polygon using ray casting algorithm
                if point_in_polygon(center_point, polygon_points):
                    current_frame_zone_tracks[zone_name].add(track_id)
        
        # Update zone tracking for each zone
        for zone_name, zone_counts in zone_analysis.items():
            # Get current frame tracks for this zone
            current_tracks = current_frame_zone_tracks.get(zone_name, set())
            
            # Update current zone tracks
            self._zone_current_track_ids[zone_name] = current_tracks
            
            # Update total zone tracks (accumulate all track IDs that have been in this zone)
            self._zone_total_track_ids[zone_name].update(current_tracks)
            
            # Update counts
            self._zone_current_counts[zone_name] = len(current_tracks)
            self._zone_total_counts[zone_name] = len(self._zone_total_track_ids[zone_name])
            
            # Create enhanced zone analysis
            enhanced_zone_analysis[zone_name] = {
                "current_count": self._zone_current_counts[zone_name],
                "total_count": self._zone_total_counts[zone_name],
                "current_track_ids": list(current_tracks),
                "total_track_ids": list(self._zone_total_track_ids[zone_name]),
                "original_counts": zone_counts  # Preserve original zone counts
            }
        
        return enhanced_zone_analysis
    
    def get_zone_tracking_info(self) -> Dict[str, Dict[str, Any]]:
        """Get detailed zone tracking information."""
        return {
            zone_name: {
                "current_count": self._zone_current_counts.get(zone_name, 0),
                "total_count": self._zone_total_counts.get(zone_name, 0),
                "current_track_ids": list(self._zone_current_track_ids.get(zone_name, set())),
                "total_track_ids": list(self._zone_total_track_ids.get(zone_name, set()))
            }
            for zone_name in set(self._zone_current_counts.keys()) | set(self._zone_total_counts.keys())
        }
    
    def get_zone_current_count(self, zone_name: str) -> int:
        """Get current count of people in a specific zone."""
        return self._zone_current_counts.get(zone_name, 0)
    
    def get_zone_total_count(self, zone_name: str) -> int:
        """Get total count of people who have been in a specific zone."""
        return self._zone_total_counts.get(zone_name, 0)
    
    def get_all_zone_counts(self) -> Dict[str, Dict[str, int]]:
        """Get current and total counts for all zones."""
        return {
            zone_name: {
                "current": self._zone_current_counts.get(zone_name, 0),
                "total": self._zone_total_counts.get(zone_name, 0)
            }
            for zone_name in set(self._zone_current_counts.keys()) | set(self._zone_total_counts.keys())
        }

    def _format_timestamp_for_stream(self, timestamp: float) -> str:
        """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
        dt = datetime.fromtimestamp(float(timestamp), tz=timezone.utc)
        return dt.strftime('%Y:%m:%d %H:%M:%S')

    def _format_timestamp_for_video(self, timestamp: float) -> str:
        """Format timestamp for video chunks (HH:MM:SS.ms format)."""
        hours = int(timestamp // 3600)
        minutes = int((timestamp % 3600) // 60)
        seconds = round(float(timestamp % 60),2)
        return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"

    def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
        """Get formatted current timestamp based on stream type."""
        print('STREAM INFO-------------------------------')
        print(stream_info)
        if not stream_info:
            return "00:00:00.00"
        if precision:
            if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
                if frame_id:
                    start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
                else:
                    start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
                stream_time_str = self._format_timestamp_for_video(start_time)
                

                return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
            else:
                return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")

        if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
            if frame_id:
                start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
            else:
                start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)

            stream_time_str = self._format_timestamp_for_video(start_time)
            
            return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
        else:
            stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
            if stream_time_str:
                try:
                    timestamp_str = stream_time_str.replace(" UTC", "")
                    dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
                    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
                    return self._format_timestamp_for_stream(timestamp)
                except:
                    return self._format_timestamp_for_stream(time.time())
            else:
                return self._format_timestamp_for_stream(time.time())

    def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
        """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
        if not stream_info:
            return "00:00:00"
        print('STARTTT STREAM INFO-------------------------------')
        print(stream_info)
        
        if precision:
            if self.start_timer is None:
                self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
                return self._format_timestamp(self.start_timer)
            elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
                self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
                return self._format_timestamp(self.start_timer)
            else:
                return self._format_timestamp(self.start_timer)

        if self.start_timer is None:
            self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
            return self._format_timestamp(self.start_timer)
        elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
            self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
            return self._format_timestamp(self.start_timer)
        
        else:
            if self.start_timer is not None:
                return self._format_timestamp(self.start_timer)

            if self._tracking_start_time is None:
                stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
                if stream_time_str:
                    try:
                        timestamp_str = stream_time_str.replace(" UTC", "")
                        dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
                        self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
                    except:
                        self._tracking_start_time = time.time()
                else:
                    self._tracking_start_time = time.time()

            dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
            dt = dt.replace(minute=0, second=0, microsecond=0)
            return dt.strftime('%Y:%m:%d %H:%M:%S')
    
    def _extract_frame_id_from_tracking(self, frame_detections: List[Dict], frame_key: str) -> str:
        """Extract frame ID from tracking data."""
        # Priority 1: Check if detections have frame information
        if frame_detections and len(frame_detections) > 0:
            first_detection = frame_detections[0]
            if "frame" in first_detection:
                return str(first_detection["frame"])
            elif "frame_id" in first_detection:
                return str(first_detection["frame_id"])
        # Priority 2: Use frame_key from input data
        return str(frame_key)
    
    def _robust_zone_total(self, zone_count):
        """Helper method to robustly calculate zone total."""
        if isinstance(zone_count, dict):
            total = 0
            for v in zone_count.values():
                if isinstance(v, int):
                    total += v
                elif isinstance(v, list):
                    total += len(v)
            return total
        elif isinstance(zone_count, list):
            return len(zone_count)
        elif isinstance(zone_count, int):
            return zone_count
        else:
            return 0
    
    # --------------------------------------------------------------------- #
    # Private helpers for canonical track aliasing                          #
    # --------------------------------------------------------------------- #

    def _compute_iou(self, box1: Any, box2: Any) -> float:
        """Compute IoU between two bounding boxes that may be either list or dict.
        Falls back to geometry_utils.calculate_iou when both boxes are dicts.
        """
        # Handle dict format directly with calculate_iou (supports many keys)
        if isinstance(box1, dict) and isinstance(box2, dict):
            return calculate_iou(box1, box2)

        # Helper to convert bbox (dict or list) to a list [x1,y1,x2,y2]
        def _bbox_to_list(bbox):
            if bbox is None:
                return []
            if isinstance(bbox, list):
                return bbox[:4] if len(bbox) >= 4 else []
            if isinstance(bbox, dict):
                if "xmin" in bbox:
                    return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
                if "x1" in bbox:
                    return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
                # Fallback: take first four values in insertion order
                values = list(bbox.values())
                return values[:4] if len(values) >= 4 else []
            # Unsupported type
            return []

        list1 = _bbox_to_list(box1)
        list2 = _bbox_to_list(box2)

        if len(list1) < 4 or len(list2) < 4:
            return 0.0

        x1_min, y1_min, x1_max, y1_max = list1
        x2_min, y2_min, x2_max, y2_max = list2

        # Ensure correct ordering of coordinates
        x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
        y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
        x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
        y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)

        inter_x_min = max(x1_min, x2_min)
        inter_y_min = max(y1_min, y2_min)
        inter_x_max = min(x1_max, x2_max)
        inter_y_max = min(y1_max, y2_max)

        inter_w = max(0.0, inter_x_max - inter_x_min)
        inter_h = max(0.0, inter_y_max - inter_y_min)
        inter_area = inter_w * inter_h

        area1 = (x1_max - x1_min) * (y1_max - y1_min)
        area2 = (x2_max - x2_min) * (y2_max - y2_min)
        union_area = area1 + area2 - inter_area

        return (inter_area / union_area) if union_area > 0 else 0.0

    def _get_canonical_id(self, raw_id: Any) -> Any:
        """Return the canonical ID for a raw tracker-generated ID."""
        return self._track_aliases.get(raw_id, raw_id)

    def _merge_or_register_track(self, raw_id: Any, bbox: List[float]) -> Any:
        """Merge the raw track into an existing canonical track if possible,
        otherwise register it as a new canonical track. Returns the canonical
        ID to use for counting.
        """
        now = time.time()

        # Fast path: raw_id already mapped
        if raw_id in self._track_aliases:
            canonical_id = self._track_aliases[raw_id]
            track_info = self._canonical_tracks.get(canonical_id)
            if track_info is not None:
                track_info["last_bbox"] = bbox
                track_info["last_update"] = now
                track_info["raw_ids"].add(raw_id)
            return canonical_id

        # Attempt to merge with an existing canonical track
        for canonical_id, info in self._canonical_tracks.items():
            # Only consider recently updated tracks to avoid stale matches
            if now - info["last_update"] > self._track_merge_time_window:
                continue

            iou = self._compute_iou(bbox, info["last_bbox"])
            if iou >= self._track_merge_iou_threshold:
                # Merge raw_id into canonical track
                self._track_aliases[raw_id] = canonical_id
                info["last_bbox"] = bbox
                info["last_update"] = now
                info["raw_ids"].add(raw_id)
                self.logger.debug(
                    f"Merged raw track {raw_id} into canonical track {canonical_id} (IoU={iou:.2f})")
                return canonical_id

        # No match found – create a new canonical track
        canonical_id = raw_id
        self._track_aliases[raw_id] = canonical_id
        self._canonical_tracks[canonical_id] = {
            "last_bbox": bbox,
            "last_update": now,
            "raw_ids": {raw_id},
        }
        self.logger.debug(f"Registered new canonical track {canonical_id}")
        return canonical_id 

    def _format_timestamp(self, timestamp: Any) -> str:
        """Format a timestamp so that exactly two digits follow the decimal point (milliseconds).

        The input can be either:
        1. A numeric Unix timestamp (``float`` / ``int``) – it will first be converted to a
           string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
        2. A string already following the same layout.

        The returned value preserves the overall format of the input but truncates or pads
        the fractional seconds portion to **exactly two digits**.

        Example
        -------
        >>> self._format_timestamp("2025-08-19-04:22:47.187574 UTC")
        '2025-08-19-04:22:47.18 UTC'
        """

        # Convert numeric timestamps to the expected string representation first
        if isinstance(timestamp, (int, float)):
            timestamp = datetime.fromtimestamp(timestamp, timezone.utc).strftime(
                '%Y-%m-%d-%H:%M:%S.%f UTC'
            )

        # Ensure we are working with a string from here on
        if not isinstance(timestamp, str):
            return str(timestamp)

        # If there is no fractional component, simply return the original string
        if '.' not in timestamp:
            return timestamp

        # Split out the main portion (up to the decimal point)
        main_part, fractional_and_suffix = timestamp.split('.', 1)

        # Separate fractional digits from the suffix (typically ' UTC')
        if ' ' in fractional_and_suffix:
            fractional_part, suffix = fractional_and_suffix.split(' ', 1)
            suffix = ' ' + suffix  # Re-attach the space removed by split
        else:
            fractional_part, suffix = fractional_and_suffix, ''

        # Guarantee exactly two digits for the fractional part
        fractional_part = (fractional_part + '00')[:2]

        return f"{main_part}.{fractional_part}{suffix}"

    def _get_tracking_start_time(self) -> str:
        """Get the tracking start time, formatted as a string."""
        if self._tracking_start_time is None:
            return "N/A"
        return self._format_timestamp(self._tracking_start_time)

    def _set_tracking_start_time(self) -> None:
        """Set the tracking start time to the current time."""
        self._tracking_start_time = time.time()

    def get_config_schema(self) -> Dict[str, Any]:
        """Get configuration schema for people counting."""
        return {
            "type": "object",
            "properties": {
                "confidence_threshold": {
                    "type": "number",
                    "minimum": 0.0,
                    "maximum": 1.0,
                    "default": 0.5,
                    "description": "Minimum confidence threshold for detections"
                },
                "enable_tracking": {
                    "type": "boolean",
                    "default": False,
                    "description": "Enable tracking for unique counting"
                },
                "zone_config": {
                    "type": "object",
                    "properties": {
                        "zones": {
                            "type": "object",
                            "additionalProperties": {
                                "type": "array",
                                "items": {
                                    "type": "array",
                                    "items": {"type": "number"},
                                    "minItems": 2,
                                    "maxItems": 2
                                },
                                "minItems": 3
                            },
                            "description": "Zone definitions as polygons"
                        },
                        "zone_confidence_thresholds": {
                            "type": "object",
                            "additionalProperties": {"type": "number", "minimum": 0.0, "maximum": 1.0},
                            "description": "Per-zone confidence thresholds"
                        }
                    }
                },
                "person_categories": {
                    "type": "array",
                    "items": {"type": "string"},
                    "default": ["person", "people"],
                    "description": "Category names that represent people"
                },
                "enable_unique_counting": {
                    "type": "boolean",
                    "default": True,
                    "description": "Enable unique people counting using tracking"
                },
                "time_window_minutes": {
                    "type": "integer",
                    "minimum": 1,
                    "default": 60,
                    "description": "Time window for counting analysis in minutes"
                },
                "alert_config": {
                    "type": "object",
                    "properties": {
                        "count_thresholds": {
                            "type": "object",
                            "additionalProperties": {"type": "integer", "minimum": 1},
                            "description": "Count thresholds for alerts"
                        },
                        "occupancy_thresholds": {
                            "type": "object", 
                            "additionalProperties": {"type": "integer", "minimum": 1},
                            "description": "Zone occupancy thresholds for alerts"
                        },
                        "alert_type": {
                            "type": "array",
                            "items": {"type": "string"},
                            "default": ["Default"],
                            "description": "To pass the type of alert. EG: email, sms, etc."
                        },
                        "alert_value": {
                            "type": "array",
                            "items": {"type": "string"},
                            "default": ["JSON"],
                            "description": "Alert value to pass the value based on type. EG: email id if type is email."
                        },
                        "alert_incident_category": {
                            "type": "array",
                            "items": {"type": "string"},
                            "default": ["Incident Detection Alert"],
                            "description": "Group and name the Alert category Type"
                        },
                    }
                }
            },
            "required": ["confidence_threshold"],
            "additionalProperties": False
        }
    
    def create_default_config(self, **overrides) -> PeopleCountingConfig:
        """Create default configuration with optional overrides."""
        defaults = {
            "category": self.category,
            "usecase": self.name,
            "confidence_threshold": 0.5,
            "enable_tracking": False,
            "enable_analytics": True,
            "enable_unique_counting": True,
            "time_window_minutes": 60,
            "person_categories": ["person", "people"],
        }
        defaults.update(overrides)
        return PeopleCountingConfig(**defaults)

    def _apply_smoothing(self, data: Any, config: PeopleCountingConfig) -> Any:
        """Apply smoothing to tracking data if enabled."""
        if self.smoothing_tracker is None:
            smoothing_config = BBoxSmoothingConfig(
                smoothing_algorithm=config.smoothing_algorithm,
                window_size=config.smoothing_window_size,
                cooldown_frames=config.smoothing_cooldown_frames,
                confidence_threshold=config.confidence_threshold or 0.5,
                confidence_range_factor=config.smoothing_confidence_range_factor,
                enable_smoothing=True
            )
            self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
        
        smoothed_data = bbox_smoothing(data, self.smoothing_tracker.config, self.smoothing_tracker)
        self.logger.debug(f"Applied bbox smoothing to tracking results")
        return smoothed_data