#!/usr/bin/env python3
"""Batch-add compilation + albumartist tags to MP3 files.

Usage:
    python3 fix-compilation-tags.py /path/to/music/
    python3 fix-compilation-tags.py --albumartist="Ray's Mix" /path/to/music/
    python3 fix-compilation-tags.py --compilation-only /path/to/music/

Fixes Plex album grouping when tracks are singles/compilations and Plex
incorrectly merges them into phantom albums. Adds:
    compilation = 1
    albumartist = "Various Artists" (customizable)

Requires: mutagen (pip install mutagen)
"""

import argparse
import os
import sys
from mutagen.easyid3 import EasyID3


def fix_tags(base: str, albumartist: str, compilation_only: bool) -> tuple[int, int]:
    """Walk base directory, add missing tags to .mp3 files. Returns (fixed, total)."""
    fixed = total = 0

    for root, dirs, files in os.walk(base):
        for f in files:
            if not f.lower().endswith(".mp3"):
                continue
            total += 1
            path = os.path.join(root, f)
            try:
                audio = EasyID3(path)
                changed = False

                if "compilation" not in audio:
                    audio["compilation"] = "1"
                    changed = True

                if not compilation_only and "albumartist" not in audio:
                    audio["albumartist"] = albumartist
                    changed = True

                if changed:
                    audio.save()
                    fixed += 1
            except Exception:
                pass  # Skip unreadable/corrupt files

            if total % 500 == 0:
                print(f"{total} scanned, {fixed} fixed...", flush=True)

    return fixed, total


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Add compilation/albumartist tags to MP3 files for Plex"
    )
    parser.add_argument(
        "directory", help="Root directory to scan recursively"
    )
    parser.add_argument(
        "--albumartist",
        default="Various Artists",
        help='albumartist value (default: "Various Artists")',
    )
    parser.add_argument(
        "--compilation-only",
        action="store_true",
        help="Only set compilation=1, skip albumartist",
    )
    args = parser.parse_args()

    base = os.path.abspath(args.directory)
    if not os.path.isdir(base):
        print(f"Error: {base} is not a directory", file=sys.stderr)
        sys.exit(1)

    print(f"Processing {base}...")
    fixed, total = fix_tags(base, args.albumartist, args.compilation_only)
    print(f"DONE: {fixed}/{total} tracks fixed")


if __name__ == "__main__":
    main()
