#!/usr/bin/env python3
import subprocess
from pathlib import Path

BASE_DIR = Path("/var/lib/ffplayout/tv-media/Shuffle-for-tv")
STAGING = BASE_DIR / "Staging"

def get_destination(title):
    t = title.lower()
    if "captain isotope" in t:
        return BASE_DIR / "captain-isotope"
    if "antimemetics" in t or "there is no antimemetics" in t:
        return BASE_DIR / "anti-memetics-division"
    if "this is ellijay" in t or "squidbillies" in t:
        return BASE_DIR / "NETV Originals/This Is Ellijay"
    if "working class music" in t:
        return BASE_DIR / "NETV Originals/working-class-music"
    if "the open stage" in t:
        return BASE_DIR / "NETV Originals/The Open Stage"
    if "appalachian football" in t or "coconut trees" in t or "community media spotlight" in t:
        return BASE_DIR / "NETV Originals"
    if any(x in t for x in ["filibus", "way down west", "le dirigeable", "protéa", "rescued in mid-air", "airship destroyer"]):
        return BASE_DIR / "silent"
    if any(x in t for x in ["bambi meets godzilla", "betty boop", "popeye", "krazy kat", "danemon ban", "oswald"]):
        return BASE_DIR / "carntoons"
    if any(x in t for x in ["spiral staircase", "secret beyond the door", "dragonwyck", "gaslight", "rebecca", "jane eyre", "big combo", "man with the golden arm", "charade", "show people", "morocco", "soup to nuts", "laurel-hardy", "animal crackers", "big parade"]):
        return BASE_DIR / "Movies"
    if any(x in t for x in ["heathersett", "small - live"]):
        return BASE_DIR / "Music"
    if any(x in t for x in ["teaser", "bumper", "commercial"]):
        return BASE_DIR / "Commercials"
    return BASE_DIR / "NETV Originals"

print("=== Normalizing + Moving All Files in Staging ===")
for file in list(STAGING.glob("*.*")):
    if file.suffix.lower() not in {".mp4", ".mkv", ".webm", ".avi"}:
        continue

    print(f"→ Processing: {file.name}")

    # Gentle normalization (your preferred settings)
    normalized = STAGING / f"{file.stem}.mp4"
    cmd = [
        "nice", "-n", "19", "ionice", "-c", "3", "ffmpeg", "-y", "-i", str(file),
        "-vf", "scale=720:480:force_original_aspect_ratio=decrease,pad=720:480:(ow-iw)/2:(oh-ih)/2",
        "-r", "30000/1001",
        "-c:v", "libx264", "-preset", "medium", "-crf", "19", "-maxrate", "10M", "-bufsize", "12M",
        "-flags", "+cgop", "-g", "30",
        "-c:a", "aac", "-b:a", "192k",
        "-movflags", "+faststart",
        str(normalized)
    ]
    subprocess.run(cmd)

    if normalized.exists():
        dest_dir = get_destination(file.name)
        dest_dir.mkdir(parents=True, exist_ok=True)
        final = dest_dir / normalized.name
        normalized.rename(final)
        print(f"✓ Moved to: {final.relative_to(BASE_DIR)}")
    else:
        print(f"✗ Failed for {file.name}")

print("\n=== All done! ===")
