"""
Transcription Worker Subprocess.
================================

This script is designed to be run as a subprocess. It:
1. Receives configuration and audio data via stdin (pickled)
2. Loads the Whisper model
3. Transcribes the audio
4. Prints the result to stdout
5. Exits (letting the OS reclaim all memory)

This ensures complete RAM/VRAM cleanup after each transcription.
"""

import sys
import pickle
import logging
import os
import traceback

# Enable debug logging to file for definitive troubleshooting
log_file = os.path.join(os.path.dirname(__file__), "worker_debug.log")
logging.basicConfig(
    level=logging.DEBUG, 
    filename=log_file, 
    filemode='w',
    format='[WORKER] %(message)s'
)

def main():
    try:
        # Read pickled data from stdin
        data = pickle.load(sys.stdin.buffer)
        
        config = data['config']
        audio_data = data['audio']
        model_path = data['model_path']
        libs_path = data['libs_path']
        
        # Add libs to PATH for cuDNN etc
        os.environ["PATH"] += os.pathsep + str(libs_path)
        
        # Import and load model
        from faster_whisper import WhisperModel
        
        config = data.get('config', {})
        model_path_arg = config.get('model_size') # Now receives full path
        device = config.get("compute_device", "cuda")
        compute = config.get("compute_type", "float16")
        
        logging.info(f"Worker initializing model from: '{model_path_arg}'")
        
        # Verify path existence for debugging
        if os.path.exists(model_path_arg):
             logging.info(f"Path verification: EXISTS. Is dir: {os.path.isdir(model_path_arg)}")
        else:
             logging.error(f"Path verification: DOES NOT EXIST!")

        model = WhisperModel(
            model_path_arg,
            device=device,
            compute_type=compute,
            download_root=model_path,
            local_files_only=True # FORCE offline mode
        )
        
        # Transcription parameters
        lang = config.get("language", "auto")
        if lang == "auto": lang = None
        
        beam_size = int(config.get("beam_size", 5))
        best_of = int(config.get("best_of", 5))
        vad = config.get("vad_filter", True)
        no_repeat_ngram = int(config.get("no_repeat_ngram_size", 0))
        condition_prev = config.get("condition_on_previous_text", True)
        
        # Transcribe with more lenient settings for challenging audio
        segments, info = model.transcribe(
            audio_data,
            beam_size=beam_size,
            best_of=best_of,
            language=lang,
            vad_filter=vad,
            vad_parameters=dict(min_silence_duration_ms=500),
            no_repeat_ngram_size=no_repeat_ngram,
            condition_on_previous_text=condition_prev,
            # Lenient thresholds for music/singing
            compression_ratio_threshold=10.0,  # Default 2.4, higher = more lenient
            log_prob_threshold=-2.0,           # Default -1.0, lower = more lenient
            no_speech_threshold=0.9,           # Default 0.6, higher = more lenient
            without_timestamps=True,           # Faster for file processing
        )
        
        text_result = ""
        for segment in segments:
            text_result += segment.text
        
        text_result = text_result.strip()
        
        # Output result as pickled data
        pickle.dump({'success': True, 'text': text_result}, sys.stdout.buffer)
        sys.stdout.buffer.flush()
        
    except Exception as e:
        # Output error with detailed traceback
        error_msg = f"{str(e)}\n{traceback.format_exc()}"
        logging.error(f"Worker failed: {error_msg}")
        pickle.dump({'success': False, 'error': error_msg}, sys.stdout.buffer)
        sys.stdout.buffer.flush()

if __name__ == "__main__":
    try:
        main()
    except Exception:
        # Catch ALL errors and print them so the user can see in the console
        import traceback
        traceback.print_exc()
        # Log to file if possible as well
        logging.error("CRITICAL WORKER CRASH")
        logging.error(traceback.format_exc())
        
        # KEY: Pause so the window doesn't close immediately
        print("\n" + "="*60)
        print("CRITICAL ERROR IN WORKER PROCESS")
        print("Please take a screenshot of this window.")
        print("="*60)
        input("Press Enter to close this window...")
