#!/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 "ellijay" in t and "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:
        return BASE_DIR / "NETV Originals"
    if any(x in t for x in ["coconut trees", "community media spotlight", "new ellijay television"]):
        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"
    # Default for anything else (teasers, bumpers, etc.)
    if any(x in t for x in ["teaser", "bumper", "commercial"]):
        return BASE_DIR / "Commercials"
    return BASE_DIR / "NETV Originals"  # safe catch-all

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

    print(f"→ Normalizing: {file.name}")
    subprocess.run(["nice", "-n", "19", "ionice", "-c", "3", "python3", str(BASE_DIR.parent / "gentle-convert.py"), str(file)])

    normalized = STAGING / f"{file.stem}.mp4"
    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"✗ Normalization failed for {file.name}")

print("\n=== All done! ===")
print("Check your folders. Let me know if anything needs adjusting.")
