#!/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"
DONE_FILE = BASE_DIR / "normalized_done.txt"

done = set()
if DONE_FILE.exists():
    done = set(DONE_FILE.read_text().splitlines())

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("=== Resumable Normalize + Move ===")
for file in list(STAGING.glob("*.*")):
    if file.suffix.lower() not in {".mp4", ".mkv", ".webm", ".avi"}:
        continue
    if file.name in done:
        print(f"Skipping (already done): {file.name}")
        continue

    temp_output = STAGING / f"normalized_{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_output)]

    if subprocess.run(cmd).returncode == 0 and temp_output.exists():
        dest_dir = get_destination(file.name)
        dest_dir.mkdir(parents=True, exist_ok=True)
        final = dest_dir / file.name
        temp_output.rename(final)
        file.unlink(missing_ok=True)
        print(f"✓ Moved to: {final.relative_to(BASE_DIR)}")
        done.add(file.name)
        DONE_FILE.write_text("\n".join(done))
    else:
        print(f"✗ Failed: {file.name}")
        temp_output.unlink(missing_ok=True)

print("\n=== Done! ===")
