#!/usr/bin/python3
import sys
import subprocess
import os
import glob

def embed_audio(video_file, audio_file, output_file):
    """
    Embeds an audio track into a video file as the first audio track.

    Parameters:
    video_file (str): Path to the video file.
    audio_file (str): Path to the audio file.
    output_file (str): Path to save the output file.
    """
    try:
        result = subprocess.run(
            [
                "ffmpeg", "-i", video_file, "-i", audio_file,
                "-c:v", "copy", "-c:a", "aac",
                "-map", "0:v:0", "-map", "1:a:0",
                "-map", "0:a?",  # Add any existing audio tracks as secondary tracks
                "-shortest", output_file, "-y"
            ],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        if result.returncode != 0:
            print(f"Error embedding audio for {video_file}: {result.stderr}")
        else:
            print(f"Audio successfully embedded: {output_file}")
    except Exception as e:
        print(f"An error occurred for {video_file}: {e}")

def main():
    # No arguments: auto-pairing mode
    if len(sys.argv) == 1:
        video_extensions = ["*.mp4", "*.mkv", "*.avi", "*.mov"]
        files_processed = 0

        for ext in video_extensions:
            for video_file in glob.glob(ext):
                base_name = os.path.splitext(video_file)[0]
                audio_file = f"{base_name}.mp3"
                if os.path.isfile(audio_file):
                    output_file = f"{base_name}_with_audio.mp4"
                    print(f"Processing: {video_file} with {audio_file} -> {output_file}")
                    embed_audio(video_file, audio_file, output_file)
                    files_processed += 1
                else:
                    print(f"No matching audio file found for: {video_file}")

        if files_processed == 0:
            print("No video-audio pairs found in the current directory.")
            sys.exit(1)

    # Explicit arguments mode
    elif len(sys.argv) == 4:
        video_file = sys.argv[1]
        audio_file = sys.argv[2]
        output_file = sys.argv[3]

        if not os.path.isfile(video_file):
            print(f"Error: Video file '{video_file}' not found.")
            sys.exit(1)
        if not os.path.isfile(audio_file):
            print(f"Error: Audio file '{audio_file}' not found.")
            sys.exit(1)

        embed_audio(video_file, audio_file, output_file)

    else:
        print("Usage:")
        print("  Auto-pairing mode (no arguments): script will pair videos and matching audio in current directory")
        print("  Explicit mode: <video_file> <audio_file> <output_file>")
        sys.exit(1)

if __name__ == "__main__":
    main()
