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

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

# Load already processed files
processed = {}
if PROCESSED.exists():
    processed = json.loads(PROCESSED.read_text())

def get_destination(title):
    t = title.lower()
    if "put on a show" in t: return BASE_DIR / "Music"
    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", "alice the", "mary and gretel", "mighty mouse"]): 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", "bucket of blood", "beat the devil", "detour", "his girl friday", "house on haunted hill", "indestructible man", "invisible avenger", "my favorite brunette", "night of the living dead", "santa claus", "the killer shrews", "the last man on earth", "the magic sword", "the stranger", "the terror"]): return BASE_DIR / "Movies"
    if any(x in t for x in ["heathersett", "small - live", "caleb bouchard", "hurly burly", "mourning person", "new clear lawn chairs", "sam burchfield"]): 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("=== Smart Normalize + Move (skips already done) ===")
for file in list(STAGING.glob("*.*")):
    if file.suffix.lower() not in {".mp4", ".mkv", ".webm", ".avi"}:
        continue
    if file.name in processed:
        print(f"Skipping (already done): {file.name}")
        continue

    dest_dir = get_destination(file.name)
    final_path = dest_dir / file.name
    if final_path.exists():
        print(f"Skipping (already in destination): {file.name}")
        processed[file.name] = True
        PROCESSED.write_text(json.dumps(processed))
        continue

    temp = STAGING / f"norm_{file.name}"
    print(f"→ Normalizing: {file.name}")

    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(temp)]

    if subprocess.run(cmd).returncode == 0 and temp.exists():
        dest_dir.mkdir(parents=True, exist_ok=True)
        temp.rename(final_path)
        file.unlink(missing_ok=True)
        print(f"✓ Moved to: {final_path.relative_to(BASE_DIR)}")
        processed[file.name] = True
        PROCESSED.write_text(json.dumps(processed))
    else:
        print(f"✗ Failed: {file.name}")
        temp.unlink(missing_ok=True)

print("\n=== Finished! ===")
print("Staging should now be clean.")
