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

from camera_streamer.camera_streamer import CameraStreamer
from camera_streamer.gstreamer_camera_streamer import GStreamerCameraStreamer, GStreamerConfig, is_gstreamer_available
from camera_streamer.gstreamer_worker_manager import GStreamerWorkerManager
from camera_streamer.worker_manager import WorkerManager
from dataclasses import dataclass
from dataclasses import dataclass, asdict
from datetime import datetime
from debug_gstreamer_gateway import DebugGStreamerGateway
from debug_stream_backend import DebugStreamBackend
from debug_streaming_gateway import DebugStreamingGateway
from debug_utils import MockSession, create_debug_input_streams, create_camera_configs_from_streams
from matrice_streaming.streaming_gateway.debug import DebugStreamingGateway, DebugStreamingAction
from matrice_streaming.streaming_gateway.debug.debug_gstreamer_gateway import DebugGStreamerGateway
from matrice_streaming.streaming_gateway.debug.debug_streaming_gateway import DebugStreamingGateway
from pathlib import Path
from streaming_gateway_utils import InputStream
import argparse
import json
import logging
import os
import psutil
import statistics
import sys
import threading
import time
import traceback

# Constants
GSTREAMER_AVAILABLE: bool = ...  # From debug_gstreamer_gateway
GSTREAMER_WORKER_AVAILABLE: bool = ...  # From debug_gstreamer_gateway
logger: Any = ...  # From test_videoplayback

# Functions
# From debug_utils
def create_camera_configs_from_streams(input_streams: List) -> List[Dict[str, Any]]: ...
    """
    Convert InputStream objects to camera configs for WorkerManager.
    
        Args:
            input_streams: List of InputStream objects
    
        Returns:
            List of camera configuration dictionaries for WorkerManager
    """

# From debug_utils
def create_debug_input_streams(video_paths: List[str], fps: int = 10, loop: bool = True) -> List: ...
    """
    Create InputStream objects for debug mode.
    
        Args:
            video_paths: List of video file paths
            fps: Frames per second
            loop: Whether to loop video files
    
        Returns:
            List of InputStream objects
    """

# From debug_utils
def create_debug_video_config(video_paths: List[str]) -> List[Dict[str, Any]]: ...
    """
    Create debug configuration from video file paths.
    
        Args:
            video_paths: List of video file paths to stream
    
        Returns:
            List of camera configurations
    """

# From example_debug_streaming
def example_basic_streaming() -> Any: ...
    """
    Basic example: Stream a single video file.
    """

# From example_debug_streaming
def example_custom_resolution() -> Any: ...
    """
    Example: Custom resolution and codec settings.
    """

# From example_debug_streaming
def example_multiple_videos() -> Any: ...
    """
    Example with multiple video files.
    """

# From example_debug_streaming
def example_save_to_files() -> Any: ...
    """
    Example: Save streamed messages to files.
    """

# From example_debug_streaming
def example_with_streaming_action() -> Any: ...
    """
    Example: Using DebugStreamingAction.
    """

# From example_debug_streaming
def main() -> Any: ...
    """
    Run all examples (or selected ones).
    """

# From test_videoplayback
def benchmark_mode(mode_name: str, gateway: Any, duration_seconds: int = 30) -> Dict[str, Any]: ...
    """
    Benchmark a single streaming mode.
    
        Args:
            mode_name: Name of the streaming mode
            gateway: Gateway instance to benchmark
            duration_seconds: How long to run the benchmark
    
        Returns:
            Dictionary with benchmark results
    """

# From test_videoplayback
def main() -> Any: ...
    """
    Benchmark all 4 streaming modes.
    """

# From test_videoplayback
def print_summary(results: List[Dict]) -> Any: ...
    """
    Print benchmark comparison summary.
    """

# From test_videoplayback
def run_mode1_benchmark(video_path: str, fps: int, duration: int) -> Optional[Dict]: ...
    """
    Benchmark Mode 1: CameraStreamer (single-threaded OpenCV).
    """

# From test_videoplayback
def run_mode2_benchmark(video_path: str, fps: int, duration: int, num_workers: int = 2) -> Optional[Dict]: ...
    """
    Benchmark Mode 2: WorkerManager (multi-process OpenCV).
    """

# From test_videoplayback
def run_mode3_benchmark(video_path: str, fps: int, duration: int) -> Optional[Dict]: ...
    """
    Benchmark Mode 3: GStreamerCameraStreamer (single-threaded GStreamer).
    """

# From test_videoplayback
def run_mode4_benchmark(video_path: str, fps: int, duration: int, num_workers: int = 2) -> Optional[Dict]: ...
    """
    Benchmark Mode 4: GStreamerWorkerManager (multi-process GStreamer).
    """

# Classes
# From benchmark
class BenchmarkResult:
    """
    Benchmark result for a single test.
    """

    def to_dict(self: Any) -> Dict[str, Any]: ...
        """
        Convert to dictionary.
        """

    def to_json(self: Any, indent: int = 2) -> str: ...
        """
        Convert to JSON string.
        """


# From benchmark
class GStreamerBenchmark:
    """
    Comprehensive benchmark suite for all streaming methods.
    """

    def __init__(self: Any, video_paths: List[str], output_dir: Optional[str] = None, log_level: int = logging.INFO) -> None: ...
        """
        Initialize benchmark suite.
        
                Args:
                    video_paths: List of video files to use for testing
                    output_dir: Directory to save benchmark results
                    log_level: Logging level
        """

    def benchmark_gstreamer_camera_streamer(self: Any, fps: int = 30, duration: float = 60.0, encoder: str = 'jpeg', codec: str = 'h264', jpeg_quality: int = 85, enable_frame_optimizer: bool = True) -> Any: ...
        """
        Benchmark GStreamerCameraStreamer (single-process GStreamer).
        
                Args:
                    fps: Target FPS
                    duration: Test duration in seconds
                    encoder: GStreamer encoder (jpeg, nvenc, x264, openh264, auto)
                    codec: Codec for hardware/software encoders (h264, h265)
                    jpeg_quality: JPEG quality (1-100)
                    enable_frame_optimizer: Enable frame similarity detection
        
                Returns:
                    BenchmarkResult with performance metrics
        """

    def benchmark_standard_camera_streamer(self: Any, fps: int = 30, duration: float = 60.0, codec: str = 'h264') -> Any: ...
        """
        Benchmark standard CameraStreamer (OpenCV + OpenH264/x264).
        
                Args:
                    fps: Target FPS
                    duration: Test duration in seconds
                    codec: Video codec (h264, h265-frame, h265-chunk)
        
                Returns:
                    BenchmarkResult with performance metrics
        """

    def print_summary(self: Any) -> Any: ...
        """
        Print benchmark summary to console.
        """

    def run_comprehensive_benchmark(self: Any, fps: int = 30, duration: float = 60.0, test_encoders: List[str] = None) -> Dict[str, Any]: ...
        """
        Run comprehensive benchmark across all methods and encoders.
        
                Args:
                    fps: Target FPS
                    duration: Test duration per benchmark
                    test_encoders: List of encoders to test (default: jpeg, nvenc, x264)
        
                Returns:
                    Dictionary with all benchmark results and comparisons
        """


# From benchmark
class ResourceMonitor:
    """
    Monitor CPU and memory usage during benchmark.
    """

    def __init__(self: Any, process: Any) -> None: ...
        """
        Initialize monitor.
        
                Args:
                    process: Process to monitor
        """

    def get_stats(self: Any) -> Dict[str, float]: ...
        """
        Get resource usage statistics.
        
                Returns:
                    Dictionary with CPU and memory stats
        """

    def start(self: Any) -> Any: ...
        """
        Start monitoring.
        """

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


# From debug_gstreamer_gateway
class DebugGStreamerGateway:
    """
    Debug version of GStreamer streaming gateway for local testing.
    
        This class allows you to test the complete GStreamer pipeline using:
        - Local video files (MP4, AVI, etc.)
        - RTSP streams
        - USB cameras
        - Test patterns
    
        Without requiring:
        - Kafka or Redis servers
        - API authentication
        - Network connectivity
        - Real streaming gateway configuration
    
        Perfect for:
        - Local development and testing
        - CI/CD pipelines
        - GStreamer encoder testing (NVENC, x264, OpenH264, JPEG)
        - Performance benchmarking
        - Frame optimization testing
    
        Example usage:
            # JPEG frame-by-frame with NVENC fallback
            gateway = DebugGStreamerGateway(
                video_paths=["video1.mp4", "video2.mp4"],
                fps=30,
                gstreamer_encoder="jpeg",
                jpeg_quality=85,
                loop_videos=True
            )
            gateway.start_streaming()
    
            # Wait and check stats
            time.sleep(30)
            stats = gateway.get_statistics()
            print(f"FPS: {stats['avg_fps']:.1f}")
            print(f"Bandwidth: {stats['bandwidth_mbps']:.2f} Mbps")
            print(f"Cache hits: {stats['cache_efficiency']:.1f}%")
    
            # Stop
            gateway.stop_streaming()
    
            # Test NVENC hardware encoding
            gateway = DebugGStreamerGateway(
                video_paths=["high_res_video.mp4"],
                fps=60,
                gstreamer_encoder="nvenc",
                gstreamer_codec="h264",
                gstreamer_preset="low-latency",
                gstreamer_gpu_id=0
            )
            gateway.start_streaming()
    """

    def __init__(self: Any, video_paths: List[str], fps: int = 30, loop_videos: bool = True, output_dir: Optional[str] = None, save_to_files: bool = False, log_messages: bool = True, save_frame_data: bool = False, width: Optional[int] = None, height: Optional[int] = None, gstreamer_encoder: str = 'jpeg', gstreamer_codec: str = 'h264', gstreamer_preset: str = 'low-latency', gstreamer_gpu_id: int = 0, jpeg_quality: int = 85, enable_frame_optimizer: bool = True, frame_optimizer_scale: float = 0.4, frame_optimizer_threshold: float = 0.05, use_workers: bool = False, num_workers: Optional[int] = None, cpu_percentage: float = 0.8, max_cameras_per_worker: int = 10) -> None: ...
        """
        Initialize debug GStreamer gateway.
        
                Args:
                    video_paths: List of video file paths to stream
                    fps: Frames per second to stream
                    loop_videos: Loop videos continuously
                    output_dir: Directory to save debug output
                    save_to_files: Save streamed messages to files
                    log_messages: Log message metadata
                    save_frame_data: Include frame data in saved files
                    width: Override video width
                    height: Override video height
                    gstreamer_encoder: GStreamer encoder (jpeg, nvenc, x264, openh264, auto)
                    gstreamer_codec: Codec for hardware/software encoders (h264, h265)
                    gstreamer_preset: NVENC preset (low-latency, high-quality, lossless)
                    gstreamer_gpu_id: GPU device ID for NVENC
                    jpeg_quality: JPEG quality 1-100 (higher=better, larger)
                    enable_frame_optimizer: Enable frame similarity detection
                    frame_optimizer_scale: Downscale factor for similarity detection
                    frame_optimizer_threshold: Similarity threshold (lower=stricter)
                    use_workers: Use multi-process GStreamerWorkerManager (Mode 4) instead of single-threaded
                    num_workers: Number of worker processes (auto-calculated if None)
                    cpu_percentage: Percentage of CPU cores to use for auto-calculation
                    max_cameras_per_worker: Maximum cameras per worker process
        """

    async def async_produce_request(self: Any, input_data: Any, topic: str, key: Optional[str] = None) -> bool: ...
        """
        Async message production for testing.
        
                Args:
                    input_data: Message data
                    topic: Topic/stream name
                    key: Message key
        
                Returns:
                    True if successful
        """

    def get_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get comprehensive streaming statistics.
        
                Returns:
                    Dictionary with streaming statistics including:
                    - Basic info (video count, fps, encoder, codec)
                    - Runtime metrics (duration, uptime)
                    - Transmission stats (frames sent, bytes, topics)
                    - Performance metrics (avg fps, bandwidth)
                    - Frame optimization metrics (cache efficiency, similarity rate)
                    - GStreamer pipeline metrics (per-stream stats)
        """

    def get_timing_stats(self: Any, stream_key: Optional[str] = None) -> Dict[str, Any]: ...
        """
        Get detailed timing statistics.
        
                Args:
                    stream_key: Specific stream or None for all
        
                Returns:
                    Timing statistics with read_time, write_time, process_time breakdown
        """

    def produce_request(self: Any, input_data: Any, topic: str, key: Optional[str] = None) -> bool: ...
        """
        Synchronous message production for testing.
        
                Args:
                    input_data: Message data
                    topic: Topic/stream name
                    key: Message key
        
                Returns:
                    True if successful
        """

    def refresh_connection_info(self: Any) -> bool: ...
        """
        Refresh connection (no-op for debug mode).
        
                Returns:
                    True (always successful in debug mode)
        """

    def reset_stats(self: Any) -> Any: ...
        """
        Reset all statistics.
        """

    def start_streaming(self: Any, block: bool = False) -> bool: ...
        """
        Start streaming all video files.
        
                Args:
                    block: If True, block until manually stopped
        
                Returns:
                    True if started successfully
        """

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


# From debug_stream_backend
class DebugStreamBackend:
    """
    Mock stream backend that logs messages instead of sending to Kafka/Redis.
    
        This allows testing the full streaming pipeline without actual message brokers.
        Messages can be:
        - Logged to console
        - Saved to JSON files
        - Counted for statistics
        - Inspected for debugging
    """

    def __init__(self: Any, output_dir: Optional[str] = None, save_to_files: bool = False, log_messages: bool = True, save_frame_data: bool = False) -> None: ...
        """
        Initialize debug stream backend.
        
                Args:
                    output_dir: Directory to save messages (if save_to_files=True)
                    save_to_files: Save messages to JSON files
                    log_messages: Log message metadata to console
                    save_frame_data: Include frame data in saved files (can be large!)
        """

    def add_message(self: Any, topic_or_channel: str, message: Dict[str, Any], key: Optional[str] = None) -> Any: ...
        """
        Add a message (mock send operation).
        
                Args:
                    topic_or_channel: Topic/channel name
                    message: Message dictionary
                    key: Message key
        """

    async def async_add_message(self: Any, topic_or_channel: str, message: Dict[str, Any], key: Optional[str] = None) -> Any: ...
        """
        Async add message (mock operation).
        """

    async def async_close(self: Any) -> Any: ...
        """
        Async close (mock operation).
        """

    async def async_setup(self: Any, topic: str) -> Any: ...
        """
        Async setup (mock operation).
        """

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

    def config(self: Any) -> Dict[str, Any]: ...
        """
        Get config (mock).
        """

    def get_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get stream statistics.
        """

    def is_async_setup(self: Any) -> bool: ...
        """
        Check if async is setup.
        """

    def setup(self: Any, topic: str) -> Any: ...
        """
        Setup a topic (mock operation).
        """


# From debug_streaming_gateway
class DebugStreamingAction:
    """
    Debug version of StreamingAction for testing without API.
    
        This is a simplified version that doesn't require action IDs, API calls,
        or health monitoring. Perfect for local testing.
    
        Example usage:
            action = DebugStreamingAction(
                video_paths=["video1.mp4", "video2.mp4"],
                fps=10
            )
            action.start()
            time.sleep(30)
            action.stop()
    """

    def __init__(self: Any, video_paths: List[str], fps: int = 10, video_codec: str = 'h265-frame', output_dir: Optional[str] = None, save_to_files: bool = False, **kwargs: Any) -> None: ...
        """
        Initialize debug streaming action.
        
                Args:
                    video_paths: List of video file paths
                    fps: Frames per second
                    video_codec: Video codec
                    output_dir: Output directory for debug files
                    save_to_files: Save messages to files
                    **kwargs: Additional arguments for DebugStreamingGateway
        """

    def get_status(self: Any) -> Dict[str, Any]: ...
        """
        Get current status.
        
                Returns:
                    Status dictionary
        """

    def start(self: Any, block: bool = False) -> bool: ...
        """
        Start streaming action.
        
                Args:
                    block: Block until manually stopped
        
                Returns:
                    True if started successfully
        """

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


# From debug_streaming_gateway
class DebugStreamingGateway:
    """
    Debug version of StreamingGateway that works without external dependencies.
    
        This class allows you to test the complete streaming pipeline using local video files
        without requiring:
        - Kafka or Redis servers
        - API authentication
        - Network connectivity
        - Real streaming gateway configuration
    
        Perfect for:
        - Local development and testing
        - CI/CD pipelines
        - Debugging encoding/processing issues
        - Performance testing
    
        Example usage:
            # Simple usage with video files
            gateway = DebugStreamingGateway(
                video_paths=["video1.mp4", "video2.mp4"],
                fps=10,
                loop_videos=True
            )
            gateway.start_streaming()
    
            # Wait and check stats
            time.sleep(30)
            print(gateway.get_statistics())
    
            # Stop
            gateway.stop_streaming()
    """

    def __init__(self: Any, video_paths: List[str], fps: int = 10, video_codec: str = 'h264', h265_quality: int = 23, use_hardware: bool = False, loop_videos: bool = True, output_dir: Optional[str] = None, save_to_files: bool = False, log_messages: bool = True, save_frame_data: bool = False, width: Optional[int] = None, height: Optional[int] = None, use_workers: bool = False, num_workers: Optional[int] = None, cpu_percentage: float = 0.8, max_cameras_per_worker: int = 10) -> None: ...
        """
        Initialize debug streaming gateway.
        
                Args:
                    video_paths: List of video file paths to stream
                    fps: Frames per second to stream
                    video_codec: Video codec (h264, h265-frame, h265-chunk)
                    h265_quality: H.265 quality (0-51, lower=better)
                    use_hardware: Use hardware encoding
                    loop_videos: Loop videos continuously
                    output_dir: Directory to save debug output
                    save_to_files: Save streamed messages to files
                    log_messages: Log message metadata
                    save_frame_data: Include frame data in saved files
                    width: Override video width
                    height: Override video height
                    use_workers: Use multi-process WorkerManager (Mode 2) instead of single-threaded CameraStreamer
                    num_workers: Number of worker processes (auto-calculated if None)
                    cpu_percentage: Percentage of CPU cores to use for auto-calculation
                    max_cameras_per_worker: Maximum cameras per worker process
        """

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

    def get_timing_stats(self: Any, stream_key: Optional[str] = None) -> Dict[str, Any]: ...
        """
        Get timing statistics.
        
                Args:
                    stream_key: Specific stream or None for all
        
                Returns:
                    Timing statistics
        """

    def reset_stats(self: Any) -> Any: ...
        """
        Reset all statistics.
        """

    def start_streaming(self: Any, block: bool = False) -> bool: ...
        """
        Start streaming all video files.
        
                Args:
                    block: If True, block until manually stopped
        
                Returns:
                    True if started successfully
        """

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


# From debug_utils
class MockRPC:
    """
    Mock RPC client for testing without real API.
    """

    def __init__(self: Any) -> None: ...

    def get(self: Any, path: str) -> Dict[str, Any]: ...
        """
        Mock GET request.
        """

    def post(self: Any, path: str, payload: Dict = None) -> Dict[str, Any]: ...
        """
        Mock POST request.
        """

    def put(self: Any, path: str, payload: Dict = None) -> Dict[str, Any]: ...
        """
        Mock PUT request.
        """


# From debug_utils
class MockSession:
    """
    Mock session for testing without authentication.
    """

    def __init__(self: Any) -> None: ...

    pass

from . import benchmark, debug_gstreamer_gateway, debug_stream_backend, debug_streaming_gateway, debug_utils, example_debug_streaming, test_videoplayback