"""
python3 ffmpeg_cmd.py "/var/www/html/2M_Shows/Tarik_El_Ward/طريق الورد ： الحلقة 1.mp4" "/var/www/html/2M_Shows/00000_TarikElWardS01E01.ts" --profile MP --resolution SD --target_aspect_ratio 4:3 --gop_size 12 --audio_language ara
python3 ffmpeg_cmd.py "/var/www/html/2M_Shows/Rosita/برامج رمضان ： الروصيطة - الحلقة 1.mp4" "/var/www/html/2M_Shows/00000_RositaS01E01.ts" --profile MP --resolution SD --target_aspect_ratio 4:3 --gop_size 12 --audio_language ara
python3 ffmpeg_cmd.py "/var/www/html/2M_Shows/Rosita/برامج رمضان ： الروصيطة - الحلقة 1.mp4" "/var/www/html/2M_Shows/00000_RositaS01E01.ts" --profile MP --resolution HD --target_aspect_ratio 16:9 --gop_size 12 --audio_language ara

python3 ffmpeg_cmd.py input_file output_file --profile MP --resolution SD --target_aspect_ratio 4:3 --gop_size 12 --audio_language ara

"""

import subprocess
import argparse

def main():
    parser = argparse.ArgumentParser(description="Convert video to MPEG-TS format with specified parameters.")
    parser.add_argument("input_file", help="Input video file path")
    parser.add_argument("output_file", help="Output MPEG-TS file path")
    parser.add_argument("--profile", choices=["MP", "HiP"], default="MP", help="H.264 profile (MP or HiP)")
    parser.add_argument("--resolution", choices=["SD", "HD"], default="SD", help="Video resolution (SD or HD)")
    parser.add_argument("--target_aspect_ratio", choices=["4:3", "16:9"], default="16:9", help="Target aspect ratio")
    parser.add_argument("--gop_size", type=int, default=12, help="GOP size (0-24)")
    parser.add_argument("--audio_language", default="eng", help="Audio language code (e.g., eng for English)")

    args = parser.parse_args()

    # Map the --profile argument to corresponding H.264 profile
    h264_profile = "main" if args.profile == "MP" else "high" if args.profile == "HiP" else "main"
    
    # Determine the video filter based on resolution
    video_filter = (
        f"scale=720:576,pad=720:(576-ih)/2:color=black" if args.target_aspect_ratio == "4:3" and args.resolution == "SD"
        else f"scale=1920:1080,interlace=1,pad=1920:(1080-ih)/2:color=black" if args.target_aspect_ratio == "16:9" and args.resolution == "HD"
        else "scale=720:576"  # Default to SD resolution if no match
    )
    
    # Determine the frame rate option based on resolution
    frame_rate_option = "-r 25i" if args.resolution == "HD" else ""

    # Determine the maximum bitrate based on resolution
    max_bitrate = "1.5M" if args.resolution == "SD" else "4M"
    mux_rate = "2M" if args.resolution == "SD" else "4.7M"

    # Validate GOP size
    if not 0 <= args.gop_size <= 24:
        print("Error: GOP size must be between 0 and 24.")
        return
    
    # FFmpeg command components
    ffmpeg_cmd = [
        "ffmpeg",                                                # FFmpeg executable
        "-i", args.input_file,                                   # Input file
        "-c:v", "libx264",                                       # Video codec: H.264
        "-preset", "slow",                                       # Encoding preset: slow 
        "-profile:v", h264_profile,                              # H.264 profile: Main (use "high" if needed)
        "-level:v", "4.1",                                       # H.264 level: 4.1
        "-vf", video_filter,                                     # Video filter: Scale to 720x576 or 1920x1080 and pad for 4:3 aspect ratio
        # frame_rate_option,                                     # Include frame rate option only for HD resolution
        "-b:v", "2M",                                            # Default bitrate (can be overridden by -maxrate)
        "-maxrate", max_bitrate,                                 # Maximum video bitrate
        "-bufsize", max_bitrate,                                 # Buffer size
        "-minrate", max_bitrate,                                 # Use the same value as maxrate for CBR
        "-g", str(args.gop_size),                                # Set GOP size
        "-keyint_min", str(args.gop_size),                       # Minimum distance between keyframes 
        "-c:a", "aac",                                           # Audio codec: AAC   
        "-strict", "experimental",                               # Use experimental AAC encoder
        "-b:a", "192k",                                          # Audio bitrate: 192 kbps
        "-muxrate", mux_rate,                                    # Maximum TS (Transport Stream) multiplexing rate
        "-f", "mpegts",                                          # Output format: MPEG-TS  
        "-c:a", "mp2",                                           # Audio codec: MPEG-1 Layer II
        "-b:a", "192k",                                          # Audio bitrate: 192 kbps
        "-ac", "2",                                              # Audio channels: Stereo 
        "-c:a", "ac3",                                           # Audio codec: Dolby Digital (AC-3)
        "-b:a", "384k",                                          # Dolby Digital bitrate: 384 kbps
        "-ac", "6",                                              # Dolby Digital channels: 5.1
        # "-c:a", "libfdk_aac",                                    # Audio codec: HE-AAC V1
        # "-b:a", "384k",                                          # Audio bitrate: 384 kbps
        "-metadata", f"language={args.audio_language}",          # Set audio language metadata
        args.output_file                                         # Output file
    ]

    # Run the FFmpeg command
    subprocess.run(ffmpeg_cmd)

if __name__ == "__main__":
    main()