import os
import json
import subprocess
import sys

def get_video_info(file_path):
    """Uses ffprobe to get detailed information about a video file."""
    command = [
        'ffprobe',
        '-v', 'error',
        '-select_streams', 'v:0',
        '-show_entries', 'stream=codec_name,width,height,avg_frame_rate,duration_ts,bit_rate,pix_fmt',
        '-of', 'json',
        file_path
    ]
    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        return json.loads(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error running ffprobe: {e}", file=sys.stderr)
        print(f"Stderr: {e.stderr}", file=sys.stderr)
        return None
    except FileNotFoundError:
        print("Error: ffprobe not found. Please ensure FFmpeg is installed and in your PATH.", file=sys.stderr)
        return None

def get_audio_info(file_path):
    """Uses ffprobe to get detailed information about an audio stream in a video file."""
    command = [
        'ffprobe',
        '-v', 'error',
        '-select_streams', 'a:0',
        '-show_entries', 'stream=codec_name,sample_rate,channels,bit_rate',
        '-of', 'json',
        file_path
    ]
    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        return json.loads(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error running ffprobe: {e}", file=sys.stderr)
        print(f"Stderr: {e.stderr}", file=sys.stderr)
        return None
    except FileNotFoundError:
        print("Error: ffprobe not found. Please ensure FFmpeg is installed and in your PATH.", file=sys.stderr)
        return None

def generate_output_path(input_file_path, output_dir, suffix="_DR_compatible", prefix="recoded_", new_extension=".mov"):
    """Generates the output file path based on input, output directory, and naming conventions."""
    base_name = os.path.basename(input_file_path)
    name_without_ext = os.path.splitext(base_name)[0]

    final_name = f"{name_without_ext}{suffix}{new_extension}"

    # Apply recoded_ prefix if output_dir is the same as input_file_path's directory
    if os.path.abspath(output_dir) == os.path.abspath(os.path.dirname(input_file_path)):
        final_name = f"{prefix}{final_name}"

    return os.path.join(output_dir, final_name)
