from integrator.phase_build import ensure_jpg, find_best_poster, get_source_video
from integrator.utils import get_state, run_shell, save_state


import json
import os


def build_master(job_dir):
    state = get_state(job_dir)
    json_path = os.path.join(job_dir, "original.info.json")
    if os.path.exists(json_path):
        with open(json_path, "r") as f: meta = json.load(f)
    else: meta = {"id": "unknown", "extractor": "unknown"}

    source_video = get_source_video(job_dir)
    source_filename = os.path.basename(source_video)

    date_str = meta.get("upload_date", "00000000")
    iso_date = f"{date_str[:4]}-{date_str[4:6]}-{date_str[6:8]}"
    basename = f"{iso_date}_{meta.get('extractor')}_{meta.get('id')}"
    volume_name = f"{meta.get('extractor')}_{meta.get('id')}"

    print(f"\n📀 --- PHASE 1: MASTER ARCHIVIERUNG (DMG) ---")
    dmg_content = os.path.join(job_dir, "dmg_content")
    os.makedirs(dmg_content, exist_ok=True)

    run_shell(f"cp '{source_video}' '{dmg_content}/{source_filename}'")
    for f in os.listdir(job_dir):
        if f.startswith("original.") and f != source_filename:
            run_shell(f"cp '{job_dir}/{f}' '{dmg_content}/{f}'")

    best_poster = find_best_poster(job_dir)
    if best_poster:
        ensure_jpg(best_poster, os.path.join(dmg_content, "poster_curated.jpg"))

    temp_dmg = os.path.join(job_dir, "temp_dmg")
    # Entferne -quiet damit man sieht, dass etwas passiert
    run_shell(f"hdiutil create -format UDTO -srcfolder '{dmg_content}' -volname '{volume_name}' '{temp_dmg}'")
    final_dmg_path = os.path.join(job_dir, f"{basename}.dmg")
    if os.path.exists(f"{temp_dmg}.cdr"): os.rename(f"{temp_dmg}.cdr", final_dmg_path)
    run_shell(f"rm -rf '{dmg_content}'")
    # Speichere dmg_name separat, da final_name später vom M4V überschrieben werden kann (bei Musikvideos)
    save_state(job_dir, {"has_master": True, "final_name": basename, "dmg_name": basename})