"""Stub file for streaming_gateway directory."""
from typing import Any, Dict, List, Optional, Union

from __future__ import annotations
from camera_streamer import CameraStreamer
from camera_streamer.ffmpeg_camera_streamer import FFmpegCameraStreamer
from camera_streamer.ffmpeg_config import FFmpegConfig, is_ffmpeg_available
from camera_streamer.ffmpeg_worker_manager import FFmpegWorkerManager
from camera_streamer.gstreamer_camera_streamer import GStreamerCameraStreamer, GStreamerConfig, is_gstreamer_available
from camera_streamer.gstreamer_worker_manager import GStreamerWorkerManager
from camera_streamer.nvdec_worker_manager import NVDECWorkerManager
from camera_streamer.nvdec_worker_manager import NVDECWorkerManager, is_nvdec_available
from camera_streamer.worker_manager import WorkerManager
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from dataclasses import dataclass, field
from dynamic_camera_manager import DynamicCameraManager
from dynamic_camera_manager import DynamicCameraManager, DynamicCameraManagerForWorkers
from dynamic_camera_manager import DynamicCameraManagerForNVDEC
from event_listener import EventListener
from kafka import KafkaProducer
from matrice_common.rpc import RPC
from matrice_common.session import Session
from matrice_common.stream import EventListener
from metrics_reporter import HeartbeatReporter
from metrics_reporter import MetricsManager, MetricsConfig
from streaming_gateway import StreamingGateway, USE_NVDEC
from streaming_gateway_utils import InputStream, StreamingGatewayUtil
from streaming_gateway_utils import StreamingGatewayUtil
from streaming_gateway_utils import StreamingGatewayUtil, InputStream, input_stream_to_camera_config, build_stream_config
from streaming_status_listener import StreamingStatusListener
import atexit
import base64
import json
import logging
import os
import re
import threading
import time

# Constants
FFMPEG_AVAILABLE: bool = ...  # From streaming_gateway
GSTREAMER_AVAILABLE: bool = ...  # From streaming_gateway
NVDEC_AVAILABLE: bool = ...  # From streaming_gateway
USE_FFMPEG: Any = ...  # From streaming_gateway
USE_GSTREAMER: Any = ...  # From streaming_gateway
USE_NVDEC: Any = ...  # From streaming_gateway

# Functions
# From streaming_gateway_utils
def build_stream_config(gateway_util: Any, server_type: str, service_id: str, stream_maxlen: Optional[int] = None) -> Dict: ...
    """
    Build stream_config dict for WorkerManager from gateway connection info.
    
        This function retrieves connection information from the API and builds
        a configuration dictionary suitable for WorkerManager and AsyncCameraWorker.
    
        Args:
            gateway_util: StreamingGatewayUtil instance for API calls
            server_type: 'kafka' or 'redis'
            service_id: Streaming gateway ID (used as service_id)
            stream_maxlen: Maximum entries per Redis stream (approximate mode, default: None = unlimited)
    
        Returns:
            Dict with connection configuration for WorkerManager
    """

# From streaming_gateway_utils
def input_stream_to_camera_config(input_stream: Any) -> Dict: ...
    """
    Convert InputStream dataclass to camera_config dict for WorkerManager.
    
        This adapter function converts the InputStream configuration format used by
        StreamingGateway to the dictionary format expected by WorkerManager and
        AsyncCameraWorker.
    
        Args:
            input_stream: InputStream dataclass instance
    
        Returns:
            Dict compatible with WorkerManager/AsyncCameraWorker
    """

# Classes
# From dynamic_camera_manager
class DynamicCameraManager:
    """
    Manages dynamic camera operations during runtime.
    
        This class handles:
        - Adding new cameras while streaming
        - Updating existing camera configurations
        - Removing cameras and stopping their streams
        - Managing camera group settings
        - Topic updates
    """

    def __init__(self: Any, camera_streamer: Any, streaming_gateway_id: str, session: Any = None, streaming_gateway: Any = None) -> None: ...
        """
        Initialize dynamic camera manager.
        
                Args:
                    camera_streamer: CameraStreamer instance to control streams
                    streaming_gateway_id: ID of the streaming gateway
                    session: Session object for API calls (optional)
                    streaming_gateway: StreamingGateway instance for updating mappings (optional)
        """

    def add_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Add a new camera and start streaming if active.
        
                Args:
                    camera_data: Camera configuration data from event
        
                Returns:
                    bool: True if camera was added successfully
        """

    def get_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get camera manager statistics.
        
                Returns:
                    Dict with statistics
        """

    def initialize_from_config(self: Any, input_streams: list) -> Any: ...
        """
        Initialize with existing input stream configurations.
        
                Args:
                    input_streams: List of InputStream objects
        """

    def remove_camera(self: Any, camera_id: str) -> bool: ...
        """
        Remove a camera and stop its stream.
        
                Args:
                    camera_id: ID of camera to remove
        
                Returns:
                    bool: True if camera was removed successfully
        """

    def remove_camera_group(self: Any, group_id: str) -> Any: ...
        """
        Remove camera group information.
        
                Args:
                    group_id: ID of camera group to remove
        """

    def update_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Update an existing camera's configuration.
        
                Handles isActive transitions:
                - If camera becomes active: Start streaming
                - If camera becomes inactive: Stop streaming but keep data
                - If camera stays active: Restart with new config
        
                Args:
                    camera_data: Updated camera configuration data
        
                Returns:
                    bool: True if camera was updated successfully
        """

    def update_camera_group(self: Any, group_data: Dict[str, Any]) -> Any: ...
        """
        Update camera group information.
        
                Args:
                    group_data: Camera group data
        """

    def update_camera_input_topic(self: Any, camera_id: str, topic_name: Optional[str]) -> Any: ...
        """
        Update input topic for a camera.
        
                Args:
                    camera_id: Camera ID
                    topic_name: New topic name (None to remove)
        """

    def update_camera_output_topic(self: Any, camera_id: str, topic_name: Optional[str]) -> Any: ...
        """
        Update output topic for a camera.
        
                Args:
                    camera_id: Camera ID
                    topic_name: New topic name (None to remove)
        """

    def update_cameras_in_group(self: Any, group_id: str, group_data: Dict[str, Any]) -> Any: ...
        """
        Update all cameras in a group with new default settings.
        
                Args:
                    group_id: Camera group ID
                    group_data: Updated group data with new default settings
        """


# From dynamic_camera_manager
class DynamicCameraManagerForNVDEC:
    """
    Dynamic camera manager for NVDEC backend (restarts workers on change).
    
        This class adapts the DynamicCameraManager interface to work with the
        NVDECWorkerManager. It converts event camera_data to NVDEC format and routes
        add/update/remove operations to the NVDECWorkerManager.
    
        Key responsibilities:
        - Convert event camera_data format to NVDEC expected format
        - Handle isActive state transitions
        - Fetch camera group settings and input topics from API
        - Track camera state and statistics
        - Update streaming gateway mappings for metrics
    """

    def __init__(self: Any, nvdec_worker_manager: Any, streaming_gateway_id: str = '', session: Any = None, streaming_gateway: Any = None) -> None: ...
        """
        Initialize dynamic camera manager for NVDEC.
        
                Args:
                    nvdec_worker_manager: NVDECWorkerManager instance to control streams
                    streaming_gateway_id: ID of the streaming gateway
                    session: Session object for API calls (optional)
                    streaming_gateway: StreamingGateway instance for updating mappings (optional)
        """

    def add_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Add a new camera via NVDECWorkerManager.
        
                Args:
                    camera_data: Camera configuration data from event
        
                Returns:
                    bool: True if camera was added successfully
        """

    def get_camera_assignments(self: Any) -> Dict[str, int]: ...
        """
        Return mapping of camera_id to GPU ID.
        """

    def get_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get camera manager statistics.
        
                Returns:
                    Dict with statistics
        """

    def initialize_from_config(self: Any, input_streams: list) -> Any: ...
        """
        Initialize with existing input stream configurations.
        
                For NVDEC flow, cameras are already started by NVDECWorkerManager,
                so this just populates the local tracking data.
        
                Args:
                    input_streams: List of InputStream objects
        """

    def is_running(self: Any) -> bool: ...
        """
        Check if the manager is currently running.
        """

    def remove_camera(self: Any, camera_id: str) -> bool: ...
        """
        Remove a camera via NVDECWorkerManager.
        
                Args:
                    camera_id: ID of camera to remove
        
                Returns:
                    bool: True if camera was removed successfully
        """

    def update_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Update an existing camera's configuration via NVDECWorkerManager.
        
                Args:
                    camera_data: Updated camera configuration data
        
                Returns:
                    bool: True if camera was updated successfully
        """


# From dynamic_camera_manager
class DynamicCameraManagerForWorkers:
    """
    Dynamic camera manager for WorkerManager-based async flow.
    
        This class adapts the DynamicCameraManager interface to work with
        the new WorkerManager + AsyncCameraWorker multiprocessing architecture.
    
        It converts event camera_data to worker camera_config format and routes
        add/update/remove operations to the WorkerManager.
    """

    def __init__(self: Any, worker_manager: Any, streaming_gateway_id: str, session: Any = None, streaming_gateway: Any = None) -> None: ...
        """
        Initialize dynamic camera manager for workers.
        
                Args:
                    worker_manager: WorkerManager instance to control streams
                    streaming_gateway_id: ID of the streaming gateway
                    session: Session object for API calls (optional)
                    streaming_gateway: StreamingGateway instance for updating mappings (optional)
        """

    def add_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Add a new camera via WorkerManager.
        
                Args:
                    camera_data: Camera configuration data from event
        
                Returns:
                    bool: True if camera was added successfully
        """

    def get_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get camera manager statistics.
        
                Returns:
                    Dict with statistics
        """

    def initialize_from_config(self: Any, input_streams: list) -> Any: ...
        """
        Initialize with existing input stream configurations.
        
                For WorkerManager flow, cameras are already started by WorkerManager,
                so this just populates the local tracking data.
        
                Args:
                    input_streams: List of InputStream objects
        """

    def remove_camera(self: Any, camera_id: str) -> bool: ...
        """
        Remove a camera via WorkerManager.
        
                Args:
                    camera_id: ID of camera to remove
        
                Returns:
                    bool: True if camera was removed successfully
        """

    def remove_camera_group(self: Any, group_id: str) -> Any: ...
        """
        Remove camera group information.
        
                Args:
                    group_id: ID of camera group to remove
        """

    def update_camera(self: Any, camera_data: Dict[str, Any]) -> bool: ...
        """
        Update an existing camera's configuration via WorkerManager.
        
                Args:
                    camera_data: Updated camera configuration data
        
                Returns:
                    bool: True if camera was updated successfully
        """

    def update_camera_group(self: Any, group_data: Dict[str, Any]) -> Any: ...
        """
        Update camera group information.
        
                Args:
                    group_data: Camera group data
        """

    def update_camera_input_topic(self: Any, camera_id: str, topic_name: Optional[str]) -> Any: ...
        """
        Update input topic for a camera.
        
                For WorkerManager flow, topics are managed within the worker config,
                so this triggers a camera update.
        
                Args:
                    camera_id: Camera ID
                    topic_name: New topic name (None to remove)
        """

    def update_camera_output_topic(self: Any, camera_id: str, topic_name: Optional[str]) -> Any: ...
        """
        Update output topic for a camera.
        
                Args:
                    camera_id: Camera ID
                    topic_name: New topic name (None to remove)
        """

    def update_cameras_in_group(self: Any, group_id: str, group_data: Dict[str, Any]) -> Any: ...
        """
        Update all cameras in a group with new default settings.
        
                For WorkerManager flow, this updates cameras via the WorkerManager.
        
                Args:
                    group_id: Camera group ID
                    group_data: Updated group data with new default settings
        """


# From event_listener
class EventListener:
    """
    Listener for camera add/update/delete events from Kafka.
    
        This class wraps the generic EventListener from matrice_common
        and provides camera-specific event handling logic.
    """

    def __init__(self: Any, session: Session, streaming_gateway_id: str, camera_manager: Any) -> None: ...
        """
        Initialize event listener.
        
                Args:
                    session: Session object for authentication
                    streaming_gateway_id: ID of streaming gateway to filter events
                    camera_manager: Camera manager instance
        """

    def get_statistics(self: Any) -> dict: ...
        """
        Get statistics.
        """

    def handle_event(self: Any, event: Dict[str, Any]) -> Any: ...
        """
        Handle camera event.
        
                Args:
                    event: Camera event dict
        """

    def is_listening(self: Any) -> bool: ...
        """
        Check if listener is active.
        """

    def start(self: Any) -> bool: ...
        """
        Start listening to camera events.
        
                Returns:
                    bool: True if started successfully
        """

    def stop(self: Any) -> Any: ...
        """
        Stop listening.
        """


# From metrics_reporter
class HeartbeatReporter:
    """
    Sends heartbeat messages to Kafka topic.
    """

    def __init__(self: Any, session: Any, streaming_gateway_id: str, topic: str = 'streaming_gateway_heartbeat', kafka_timeout: float = 5.0) -> None: ...
        """
        Initialize heartbeat reporter.
        
        Args:
            session: Session object for API calls
            streaming_gateway_id: ID of the streaming gateway
            topic: Kafka topic to send heartbeats to (default: streaming_gateway_heartbeat)
            kafka_timeout: Timeout for Kafka operations
        """

    def close(self: Any) -> Any: ...
        """
        Close Kafka producer.
        """

    def send_heartbeat(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Send heartbeat to Kafka topic.
        
        Args:
            camera_config: Camera configuration payload to send
        
        Returns:
            True if successful, False otherwise
        """


# From metrics_reporter
class MetricsCalculator:
    """
    Calculate statistical metrics over time windows.
    """

    def calculate_fps(frame_count_start: int, frame_count_end: int, time_elapsed: float) -> float: ...
        """
        Calculate frames per second.
        
        Args:
            frame_count_start: Starting frame count
            frame_count_end: Ending frame count
            time_elapsed: Time elapsed in seconds
        
        Returns:
            Frames per second
        """

    def calculate_statistics(values: List[float]) -> Dict[str, float]: ...
        """
        Calculate min, max, avg, p0, p50, p100 from a list of values.
        
        Args:
            values: List of numeric values
        
        Returns:
            Dictionary with statistical metrics
        """


# From metrics_reporter
class MetricsCollector:
    """
    Collects and aggregates streaming gateway metrics.
    """

    def __init__(self: Any, streaming_gateway: Any, config: Any) -> None: ...
        """
        Initialize metrics collector.
        
        Args:
            streaming_gateway: StreamingGateway instance
            config: Metrics configuration
        """

    def add_to_history(self: Any, snapshot: Dict[str, Any]) -> Any: ...
        """
        Add snapshot to rolling history window.
        
        Args:
            snapshot: Metrics snapshot to add
        """

    def collect_snapshot(self: Any) -> Dict[str, Any]: ...
        """
        Collect current metrics snapshot from streaming gateway.
        
        Returns:
            Dictionary containing current metrics state
        """

    def get_aggregated_metrics(self: Any) -> Optional[Dict[str, Any]]: ...
        """
        Calculate aggregated metrics from accumulated timing history.
        
        Returns:
            Dictionary with aggregated per-camera metrics
        """


# From metrics_reporter
class MetricsConfig:
    """
    Configuration for metrics collection and reporting.
    """

    pass

# From metrics_reporter
class MetricsManager:
    """
    Main orchestrator for metrics collection and reporting.
    
    This class coordinates the collection of metrics from the streaming gateway,
    calculates statistics, and reports them via Kafka.
    """

    def __init__(self: Any, streaming_gateway: Any, session: Any, streaming_gateway_id: str, action_id: Optional[str] = None, config: Optional[MetricsConfig] = None) -> None: ...
        """
        Initialize metrics manager.
        
        Args:
            streaming_gateway: StreamingGateway instance
            session: Session object for API calls
            streaming_gateway_id: ID of the streaming gateway
            action_id: Optional action ID
            config: Optional metrics configuration (uses default if not provided)
        """

    def collect_and_report(self: Any) -> Any: ...
        """
        Collect current metrics and report if interval has elapsed.
        
        This method should be called periodically (e.g., every 1-30 seconds)
        from the health monitoring loop.
        """

    def stop(self: Any) -> Any: ...
        """
        Stop metrics collection and close resources.
        """


# From metrics_reporter
class MetricsReporter:
    """
    Sends metrics to Kafka topic.
    """

    def __init__(self: Any, session: Any, streaming_gateway_id: str, config: Any) -> None: ...
        """
        Initialize metrics reporter.
        
        Args:
            session: Session object for API calls
            streaming_gateway_id: ID of the streaming gateway
            config: Metrics configuration
        """

    def close(self: Any) -> Any: ...
        """
        Close Kafka producer.
        """

    def send_metrics(self: Any, metrics: Dict[str, Any]) -> bool: ...
        """
        Send metrics to Kafka topic.
        
        Args:
            metrics: Metrics payload to send
        
        Returns:
            True if successful, False otherwise
        """


# From streaming_action
class StreamingAction:
    """
    High-level orchestrator for streaming gateway lifecycle management.
    
    This class automates the entire streaming process:
    1. Fetches configuration from API using streaming_gateway_id
    2. Sets up StreamingGateway with proper configuration
    3. Starts streaming with status updates to API
    4. Monitors streaming health
    5. Periodically checks if action ID matches streaming gateway's actionRecordID
    6. Automatically stops if action ID mismatch is detected
    7. Handles errors and recovery
    8. Provides clean shutdown
    
    Example usage:
        orchestrator = StreamingAction(
            session=session,
            action_id="your_action_id",
            action_id_check_interval=30.0,  # Check every 30 seconds
        )
    
        # Start streaming (auto-fetches config, sets up, and starts)
        if orchestrator.start():
            logging.info("Streaming started successfully!")
    
            # Monitor for a while
            time.sleep(60)
    
            # Stop when done
            orchestrator.stop()
        else:
            logging.error("Failed to start streaming")
    """

    def __init__(self: Any, session: Session, action_id: str, enable_intelligent_transmission: bool = True, monitoring_interval: float = 30.0, auto_restart: bool = True, max_restart_attempts: int = 3, action_id_check_interval: float = 600.0, enable_event_listening: bool = True, allow_empty_start: bool = True) -> None: ...
        """
        Initialize StreamingAction.
        
                Args:
                    session: Session object for authentication
                    action_id: ID of the action to manage
                    enable_intelligent_transmission: Whether to enable intelligent frame transmission
                    monitoring_interval: Interval in seconds between health checks and heartbeats (default: 30 seconds)
                    auto_restart: Whether to automatically restart on failures
                    max_restart_attempts: Maximum number of restart attempts before giving up
                    action_id_check_interval: Interval in seconds between checks to verify action ID matches streaming gateway
                    enable_event_listening: Enable dynamic event listening for configuration updates
                    allow_empty_start: Allow starting with zero cameras (default True). Cameras can be added dynamically.
        """

    def check_action_id_matches(self: Any) -> bool: ...
        """
        Check if the current action ID matches the streaming gateway's actionRecordID.
        
        Handles transient errors gracefully:
        - 502 Bad Gateway: Skip check, continue streaming (server temporarily unavailable)
        - 404 Not Found: Stop streaming (gateway may be deleted)
        - Other API errors: Skip check, continue streaming (don't stop on transient issues)
        
        Returns:
            bool: True if action ID matches or check should be skipped, False if mismatch or gateway deleted
        """

    def get_status(self: Any) -> Dict: ...
        """
        Get current orchestrator status and statistics.
        
        Returns:
            Dict: Complete status information
        """

    def is_healthy(self: Any) -> bool: ...
        """
        Check if the orchestrator is healthy.
        
        Returns:
            bool: True if healthy, False otherwise
        """

    def restart(self: Any) -> bool: ...
        """
        Restart the streaming orchestrator.
        
        Returns:
            bool: True if restarted successfully, False otherwise
        """

    def start(self: Any, block: bool = True) -> bool: ...
        """
        Start the streaming orchestrator.
        
        This method:
        1. Fetches streaming configuration from API
        2. Creates and configures StreamingGateway
        3. Starts streaming with API status updates
        4. Starts health monitoring
        
        Args:
            block: Whether to block the thread until the streaming gateway is started (default: True)
        
        Returns:
            bool: True if started successfully, False otherwise
        """

    def stop(self: Any) -> bool: ...
        """
        Stop the streaming orchestrator.
        
        Returns:
            bool: True if stopped successfully, False otherwise
        """

    def update_status(self: Any, step_code: str, status: str, status_description: str) -> None: ...
        """
        Update the status of the data processing job.
        """


# From streaming_gateway
class StreamingGateway:
    """
    Simplified streaming gateway for managing camera streams.
    """

    def __init__(self: Any, session: Any, streaming_gateway_id: Optional[str] = None, server_id: Optional[str] = None, server_type: Optional[str] = None, inputs_config: Optional[List[InputStream]] = None, video_codec: Optional[str] = None, force_restart: bool = False, enable_event_listening: bool = True, action_id: Optional[str] = None, use_async_workers: bool = True, num_workers: Optional[int] = None, max_cameras_per_worker: int = 50, allow_empty_start: bool = True, use_gstreamer: bool = False, gstreamer_encoder: str = 'auto', gstreamer_codec: str = 'h264', gstreamer_preset: str = 'low-latency', gstreamer_gpu_id: int = 0, gstreamer_platform: str = 'auto', gstreamer_use_hardware_decode: bool = True, gstreamer_use_hardware_jpeg: bool = True, gstreamer_jetson_use_nvmm: bool = True, gstreamer_frame_optimizer_mode: str = 'hash-only', gstreamer_fallback_on_error: bool = True, gstreamer_verbose_logging: bool = False, use_ffmpeg: bool = USE_FFMPEG, ffmpeg_hwaccel: str = 'auto', ffmpeg_threads: int = 1, ffmpeg_low_latency: bool = True, ffmpeg_pixel_format: str = 'bgr24', use_nvdec: bool = USE_NVDEC, nvdec_gpu_id: int = 0, nvdec_num_gpus: int = 0, nvdec_pool_size: int = 8, nvdec_burst_size: int = 4, nvdec_frame_width: int = 640, nvdec_frame_height: int = 640, nvdec_num_slots: int = 32, nvdec_target_fps: int = 0, shm_slot_count: int = 1000) -> None: ...
        """
        Initialize StreamingGateway.
        
                Args:
                    session: Session object for authentication
                    streaming_gateway_id: ID of the streaming gateway
                    server_id: ID of the server (Kafka/Redis)
                    server_type: Type of server (kafka or redis)
                    inputs_config: List of InputStream configurations
                    video_codec: Video codec (h264 or h265)
                    force_restart: Force stop existing streams and restart
                    enable_event_listening: Enable dynamic event listening for configuration updates
                    action_id: Optional action ID to pass in API requests
                    use_async_workers: Use new async worker flow (default True)
                    num_workers: Number of worker processes for async flow
                    max_cameras_per_worker: Maximum cameras per worker process
                    allow_empty_start: Allow starting with zero cameras (default True)
                    use_gstreamer: Use GStreamer-based encoding (default False)
                    gstreamer_encoder: GStreamer encoder type (auto, nvenc, x264, openh264, jpeg)
                    gstreamer_codec: GStreamer codec (h264, h265)
                    gstreamer_preset: NVENC preset for hardware encoding
                    gstreamer_gpu_id: GPU device ID for NVENC hardware encoding
                    gstreamer_platform: Platform override (auto, jetson, desktop-gpu, intel, amd, cpu)
                    gstreamer_use_hardware_decode: Enable hardware decode (nvv4l2decoder, nvdec, vaapi)
                    gstreamer_use_hardware_jpeg: Enable hardware JPEG encoding when available
                    gstreamer_jetson_use_nvmm: Use NVMM zero-copy memory on Jetson devices
                    gstreamer_frame_optimizer_mode: Frame optimization mode (hash-only, dual-appsink, disabled)
                    gstreamer_fallback_on_error: Automatically fallback to CPU pipeline on hardware errors
                    gstreamer_verbose_logging: Enable verbose pipeline construction logging
                    use_ffmpeg: Use FFmpeg subprocess-based encoding (alternative to OpenCV/GStreamer)
                    ffmpeg_hwaccel: FFmpeg hardware acceleration (auto, cuda, vaapi, none)
                    ffmpeg_threads: Number of FFmpeg decode threads per stream
                    ffmpeg_low_latency: Enable FFmpeg low-latency flags
                    ffmpeg_pixel_format: Output pixel format (bgr24, rgb24, nv12)
                    use_nvdec: Use NVDEC hardware decode with CUDA IPC output (requires CuPy, PyNvVideoCodec)
                    nvdec_gpu_id: Primary/starting GPU device ID for round-robin camera assignment
                    nvdec_num_gpus: Number of GPUs to use (0=auto-detect all available GPUs)
                    nvdec_pool_size: Number of NVDEC decoders per GPU
                    nvdec_burst_size: Frames per stream before rotating to next stream
                    nvdec_frame_width: Default output frame width (used if camera config doesn't specify)
                    nvdec_frame_height: Default output frame height (used if camera config doesn't specify)
                    nvdec_num_slots: Ring buffer slots per camera (named by camera_id)
                    nvdec_target_fps: Global FPS override (0=use per-camera FPS from camera config)
                    shm_slot_count: Number of frame slots per camera ring buffer for SHM mode (default: 300)
        """

    def get_camera_id_for_stream_key(self: Any, stream_key: str) -> Optional[str]: ...
        """
        Get camera_id for a given stream_key.
        """

    def get_config(self: Any) -> Dict: ...
        """
        Get current configuration.
        """

    def get_statistics(self: Any) -> Dict: ...
        """
        Get streaming statistics.
        """

    def start_streaming(self: Any) -> bool: ...
        """
        Start streaming.
        
                Returns:
                    bool: True if streaming started successfully, False otherwise
        """

    def stop_streaming(self: Any) -> None: ...
        """
        Stop all streaming operations.
        """


# From streaming_gateway_utils
class InputStream:
    """
    Configuration for input sources.
    """

    pass

# From streaming_gateway_utils
class StreamingGatewayUtil:
    def __init__(self: Any, session: Session, streaming_gateway_id: str, server_id: Optional[str] = None, action_id: Optional[str] = None) -> None: ...

    def get_and_wait_for_connection_info(self: Any, server_type: Optional[str] = None, server_id: Optional[str] = None, connection_timeout: int = 300) -> Dict: ...
        """
        Get and wait for connection information for the streaming gateway.
        
                Args:
                    server_type: Type of server ('kafka' or 'redis'). Required.
                    server_id: ID of the server. If not provided, uses self.server_id.
                    connection_timeout: Timeout in seconds to wait for connection info (default: 300).
        
                Returns:
                    Dict: Connection configuration
        
                Raises:
                    ValueError: If server_type or server_id is not provided
                    RuntimeError: If timeout is reached while waiting for connection info
        """

    def get_camera_groups(self: Any) -> Any: ...

    def get_cameras(self: Any) -> Any: ...

    def get_input_streams(self: Any) -> List[InputStream]: ...
        """
        Get cameras as list of InputStream objects with proper configuration.
        """

    def get_nvdec_input_streams(self: Any, mediamtx_host: str = 'localhost', mediamtx_port: int = 8554) -> List[InputStream]: ...
        """
        Get camera input streams with MediaMTX RTSP URLs for NVDEC hardware decode.
        
                This method fetches cameras from the streaming gateway API and constructs
                RTSP URLs pointing to the local MediaMTX server for each camera. Used by the
                CUDA SHM / NVDEC inference pipeline where frames are decoded on GPU via
                GStreamer NVDEC instead of the CPU-based AsyncCameraWorker flow.
        
                All camera types (RTSP and FILE) use the MediaMTX RTSP URL as their source,
                since MediaMTX handles both live RTSP relay and file playback.
        
                Args:
                    mediamtx_host: MediaMTX server hostname (default: "localhost")
                    mediamtx_port: MediaMTX server RTSP port (default: 8554)
        
                Returns:
                    List[InputStream]: Camera configurations with MediaMTX RTSP URLs as source
        """

    def get_simulated_stream_url(self: Any, camera_id: str) -> Any: ...

    def get_streaming_gateway_by_id(self: Any) -> Any: ...

    def get_streaming_input_topics(self: Any) -> Any: ...

    def get_streaming_output_topics(self: Any) -> Any: ...

    def send_heartbeat(self: Any, camera_config: Optional[Dict] = None) -> bool: ...
        """
        Send a heartbeat to the streaming gateway via Kafka.
        
        Args:
            camera_config: Camera configuration data to include in heartbeat
                           Should contain 'cameras' list and 'stats' dict
        
        Returns:
            bool: True if heartbeat sent successfully, False otherwise
        """

    def start_streaming(self: Any) -> Optional[Dict]: ...
        """
        Start the streaming gateway.
        
        Returns:
            Dict: API response data or None if failed
        """

    def stop_streaming(self: Any) -> None: ...
        """
        Stop the streaming gateway.
        
        Returns:
            Dict: API response data or None if failed
        """

    def update_status(self: Any, status: str) -> None: ...
        """
        Update the status of the streaming gateway.
        
        Args:
            status: New status (active, inactive, starting, stopped, etc.)
        
        Returns:
            Dict: API response data or None if failed
        """


# From streaming_status_listener
class StreamingStatusListener:
    """
    Listener for streaming gateway status events from Kafka.
    
        This class listens to the Streaming_Events_Status topic and triggers
        a callback when a stop command is received for this gateway.
    """

    def __init__(self: Any, session: Session, streaming_gateway_id: str, action_id: str, on_stop_callback: Any) -> None: ...
        """
        Initialize status listener.
        
                Args:
                    session: Session object for authentication
                    streaming_gateway_id: ID of streaming gateway to filter events
                    action_id: ID of action record to filter events
                    on_stop_callback: Callback function to invoke when stop event is received
        """

    def get_statistics(self: Any) -> dict: ...
        """
        Get statistics.
        """

    def handle_event(self: Any, event: dict) -> Any: ...
        """
        Handle status event.
        
                Args:
                    event: Status event dict with eventType, streamingGatewayId, timestamp
        """

    def is_listening(self: Any) -> bool: ...
        """
        Check if listener is active.
        """

    def start(self: Any) -> bool: ...
        """
        Start listening to status events.
        
                Returns:
                    bool: True if started successfully
        """

    def stop(self: Any) -> Any: ...
        """
        Stop listening.
        """


from . import dynamic_camera_manager, event_listener, metrics_reporter, streaming_action, streaming_gateway, streaming_gateway_utils, streaming_status_listener