import os
import shutil
import time
import json
from pathlib import Path
from datetime import datetime

def _find_best_candidate(files, extensions, keyword_prio=None, exclude=None):
    candidates = [f for f in files if f.lower().endswith(tuple(extensions))]
    
    if exclude:
        candidates = [f for f in candidates if exclude not in f]
        
    if not candidates: return None
        
    if keyword_prio:
        for keyword in keyword_prio:
            for c in candidates:
                if keyword in c: return c
                    
    # Fallback: Größte Datei gewinnt
    candidates.sort(key=lambda x: os.path.getsize(x), reverse=True)
    return candidates[0]

def normalize_job_structure(source_dir, target_job_dir):
    """
    Analysiert Quellordner und kopiert Video/JSON/Bilder sauber 
    in den target_job_dir (original.mp4, original.info.json etc.).
    """
    source_path = Path(source_dir)
    # Alle Dateien rekursiv (keine versteckten)
    all_files = [str(f) for f in source_path.rglob("*") if f.is_file() and not f.name.startswith(".")]
    
    print(f"   🔍 Analysiere {len(all_files)} Dateien...")
    os.makedirs(target_job_dir, exist_ok=True)

    # 1. VIDEO
    video_exts = (".mkv", ".mp4", ".webm", ".mov", ".avi", ".m4v")
    video_file = _find_best_candidate(all_files, video_exts, keyword_prio=["original", "source", "video"], exclude="rendition")
    
    if not video_file:
        raise FileNotFoundError("Keine Videodatei gefunden!")
    
    vid_ext = os.path.splitext(video_file)[1]
    shutil.copy2(video_file, os.path.join(target_job_dir, f"original{vid_ext}"))
    print(f"   ✅ Video: {os.path.basename(video_file)}")

    # 2. METADATEN
    json_file = _find_best_candidate(all_files, (".json",), keyword_prio=["original.info", "source.info", ".info"], exclude="sponsor")
    final_json_path = os.path.join(target_job_dir, "original.info.json")
    
    if json_file:
        shutil.copy2(json_file, final_json_path)
    else:
        print("   ⚠️  Keine Info-JSON. Erstelle Dummy.")
        stat = os.stat(video_file)
        dt = datetime.fromtimestamp(stat.st_mtime)
        dummy_meta = {
            "id": f"migrated_{int(time.time())}",
            "extractor": "migration",
            "title": os.path.basename(video_file),
            "upload_date": dt.strftime("%Y%m%d"),
            "description": "Automatisch migriert."
        }
        with open(final_json_path, "w") as f:
            json.dump(dummy_meta, f, indent=4)

    # 3. THUMBNAIL
    img_file = _find_best_candidate(all_files, (".webp", ".jpg", ".png"), keyword_prio=["poster", "thumb", "source"], exclude=None)
    if img_file:
        img_ext = os.path.splitext(img_file)[1]
        shutil.copy2(img_file, os.path.join(target_job_dir, f"original{img_ext}"))

    # 4. UNTERTITEL
    vtts = [f for f in all_files if f.endswith(".vtt") or f.endswith(".srt")]
    for vtt in vtts:
        base = os.path.basename(vtt)
        target_name = f"original.{base}" if "original" not in base else base
        shutil.copy2(vtt, os.path.join(target_job_dir, target_name))