#!/usr/bin/env python3
"""
Mirror a folder structure, converting WAV files to MP3 using ffmpeg.
All other files (images, scripts, etc.) are copied as-is.
"""

import os
import shutil
import subprocess
import sys
from pathlib import Path


def convert_structure(src_root: Path, dst_root: Path, bitrate: str = "192k") -> None:
    for src_dir, dirs, files in os.walk(src_root):
        src_dir = Path(src_dir)

        # Skip macOS noise
        dirs[:] = [d for d in dirs if d not in {".DS_Store", "__MACOSX"}]

        rel = src_dir.relative_to(src_root)
        dst_dir = dst_root / rel
        dst_dir.mkdir(parents=True, exist_ok=True)

        for fname in files:
            if fname.startswith("."):          # .DS_Store etc.
                continue

            src_file = src_dir / fname
            suffix = src_file.suffix.lower()

            if suffix == ".wav":
                dst_file = dst_dir / (src_file.stem + ".mp3")
                if dst_file.exists():
                    print(f"  skip (exists): {dst_file}")
                    continue
                print(f"  convert: {src_file.relative_to(src_root)}")
                result = subprocess.run(
                    [
                        "ffmpeg", "-y",
                        "-i", str(src_file),
                        "-codec:a", "libmp3lame",
                        "-b:a", bitrate,
                        "-id3v2_version", "3",
                        str(dst_file),
                    ],
                    capture_output=True,
                    text=True,
                )
                if result.returncode != 0:
                    print(f"    ERROR: {result.stderr.splitlines()[-1]}", file=sys.stderr)
            else:
                dst_file = dst_dir / fname
                if dst_file.exists():
                    print(f"  skip (exists): {dst_file}")
                    continue
                print(f"  copy:    {src_file.relative_to(src_root)}")
                shutil.copy2(src_file, dst_file)


def main():
    import argparse

    parser = argparse.ArgumentParser(
        description="Mirror a folder tree, converting WAV → MP3 via ffmpeg."
    )
    parser.add_argument("src", help="Source root directory")
    parser.add_argument("dst", help="Destination root directory (created if absent)")
    parser.add_argument(
        "--bitrate", default="192k",
        help="MP3 bitrate (default: 192k). Use 320k for highest quality."
    )
    args = parser.parse_args()

    src = Path(args.src).expanduser().resolve()
    dst = Path(args.dst).expanduser().resolve()

    if not src.exists():
        sys.exit(f"Source not found: {src}")
    if dst == src:
        sys.exit("Source and destination must differ.")

    print(f"Source : {src}")
    print(f"Dest   : {dst}")
    print(f"Bitrate: {args.bitrate}\n")

    convert_structure(src, dst, bitrate=args.bitrate)
    print("\nDone.")


if __name__ == "__main__":
    main()

