"""
Clean, minimal pipeline logger.

Provides consistent, single-line logging format:
    [GPU0] PICK   dQw4w9WgXcQ
    [GPU0] 1/9   Download      2.1s
    [GPU0] DONE  dQw4w9WgXcQ  18.7s | 12.3min | 5 spk | 72%
"""

from typing import Optional
import sys


class PipelineLogger:
    """Clean, minimal pipeline logger for worker processes."""

    def __init__(self, gpu_id: int):
        self.gpu_id = gpu_id
        self.prefix = f"[GPU{gpu_id}]"
        self.video_id: Optional[str] = None
        self.total_stages: int = 9

    def set_video(self, video_id: str, total_stages: int = 9):
        """Set current video context."""
        self.video_id = video_id
        self.total_stages = total_stages

    def pick(self, video_id: str):
        """Log video picked for processing."""
        self._print(f"PICK   {video_id}")

    def stage(self, num: int, name: str, duration: float, extra: str = ""):
        """Log stage completion."""
        name_padded = name[:12].ljust(12)
        msg = f"{num}/{self.total_stages:<2} {name_padded} {duration:>5.1f}s"
        if extra:
            msg += f"  | {extra}"
        self._print(msg)

    def upload(self, video_id: str, duration: float, size_mb: float):
        """Log upload completion."""
        self._print(f"UPLOAD {video_id} {duration:.1f}s | {size_mb:.1f}MB")

    def done(self, video_id: str, total_time: float, audio_min: float,
             speakers: int, usable_pct: float):
        """Log successful completion."""
        self._print(f"DONE   {video_id} {total_time:.1f}s | {audio_min:.1f}min | {speakers} spk | {usable_pct:.0f}%")

    def fail(self, video_id: str, error: str):
        """Log failure with full error message."""
        self._print(f"FAIL   {video_id} | {error}")

    def skip(self, video_id: str, reason: str):
        """Log skipped video."""
        self._print(f"SKIP   {video_id} | {reason}")

    def info(self, message: str):
        """Log general info message."""
        self._print(message)

    def _print(self, message: str):
        """Print with GPU prefix, flush immediately."""
        print(f"{self.prefix} {message}", flush=True)


def silence_verbose_loggers():
    """Silence verbose third-party and internal loggers."""
    import logging
    import warnings
    import os

    # Suppress Python warnings
    warnings.filterwarnings('ignore', category=FutureWarning)
    warnings.filterwarnings('ignore', category=UserWarning)
    warnings.filterwarnings('ignore', message='.*torchaudio.*')
    warnings.filterwarnings('ignore', message='.*deprecated.*')

    # Suppress torch hub "Using cache found" messages
    os.environ['TORCH_HUB_VERBOSE'] = '0'

    # Suppress torch.hub loading messages by setting _HUBCONF_VERBOSE
    try:
        import torch.hub
        torch.hub._VERBOSE = False
    except (ImportError, AttributeError):
        pass

    # Set root logging level to WARNING to catch misc debug logs
    logging.getLogger().setLevel(logging.WARNING)

    # Set verbose loggers to ERROR level (more aggressive than WARNING)
    verbose_loggers = [
        # Internal pipeline loggers
        'FastPipelineV6',
        'FastPipelineV5',
        'FastPipelineV6.Pipeline',
        'FastPipelineV6.Download',
        'FastPipelineV6.VAD',
        'FastPipelineV6.Diarization',
        'FastPipelineV6.Embeddings',
        'FastPipelineV6.UnifiedEmbeddings',
        'FastPipelineV6.Clustering',
        'FastPipelineV6.ChunkReassignment',
        'FastPipelineV6.MusicDetection',
        'FastPipelineV6.HybridMusicDetection',
        'FastPipelineV6.SpectralAnalysis',
        'FastPipelineV6.OSD',
        'FastPipelineV6.BoundaryRefinement',
        'FastPipelineV6.AudioBuffer',
        'FastPipelineV6.Models',
        'FastPipelineV6.Export',
        'FastPipelineV5.Utils',
        'FastPipelineV5.Compute',
        'FastPipelineV5.Clustering',
        'SupabaseClient',
        'R2Client',
        'WorkerPools',
        'ChunkParallel',
        # Third-party - speechbrain (all submodules)
        'speechbrain',
        'speechbrain.utils',
        'speechbrain.utils.checkpoints',
        'speechbrain.utils.fetching',
        'speechbrain.utils.parameter_transfer',
        'speechbrain.dataio',
        'speechbrain.dataio.encoder',
        # Third-party - pyannote
        'pyannote',
        'pyannote.audio',
        'pyannote.audio.pipelines',
        # Third-party - others
        'torch',
        'torchaudio',
        'transformers',
        'urllib3',
        'httpx',
        'httpcore',
        'numba',
        'filelock',
    ]

    for name in verbose_loggers:
        logging.getLogger(name).setLevel(logging.ERROR)
