"""
fix_subtitle_names.py
Post-procesa los archivos .vtt descargados por scrape_subtitles.py:
- Detecta idioma por contenido cuando el nombre es 'unknown'
- Renombra correctamente a {num}-es.vtt y {num}-en.vtt
- Actualiza course_content.json con los paths correctos
- Luego ejecuta build_course_map.py + raio:import para sincronizar DB
"""
import json
import re
import sys
import subprocess
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8")

SCRIPTS_DIR  = Path(__file__).parent
BASE_DIR     = SCRIPTS_DIR.parent
SUBS_DIR     = BASE_DIR / "public" / "subtitles"
CONTENT_FILE = SCRIPTS_DIR / "course_content.json"

# Strong Spanish indicator words (unlikely in English text)
SPANISH_WORDS = re.compile(
    r'\b(que|para|cómo|está|también|sería|tengo|tiene|pero|esto|eso|porque|cuando|donde|'
    r'todo|muy|más|así|aquí|ahora|antes|después|siempre|nunca|sólo|sino|mientras|'
    r'vamos|voy|quiero|puedo|hola|gracias|señor|señora)\b',
    re.I | re.U
)

ENGLISH_WORDS = re.compile(
    r'\b(the|and|that|this|with|have|from|they|been|what|when|which|would|could|'
    r'should|about|there|their|through|because|before|after|during|while|always|'
    r'never|going|hello|thank|please|sorry|really|actually|exactly)\b',
    re.I
)


def detect_language(vtt_path: Path) -> str:
    """Returns 'es', 'en', or 'unknown'."""
    try:
        text = vtt_path.read_text(encoding="utf-8", errors="ignore")
        # Use a good chunk of text, skip the header
        body = "\n".join(text.splitlines()[10:])[:2000]
        es_hits = len(SPANISH_WORDS.findall(body))
        en_hits = len(ENGLISH_WORDS.findall(body))
        if es_hits > en_hits and es_hits >= 3:
            return "es"
        if en_hits > es_hits and en_hits >= 3:
            return "en"
        # Tiebreaker: Spanish has accented chars more often
        accent_count = len(re.findall(r'[áéíóúüñ¿¡]', body, re.I))
        return "es" if accent_count >= 2 else "en"
    except Exception:
        return "unknown"


def main():
    if not SUBS_DIR.exists():
        print("No existe directorio de subtítulos")
        return

    content = json.loads(CONTENT_FILE.read_text(encoding="utf-8"))
    content_by_num = {l["num"]: l for l in content}

    # Process all lesson numbers that have subtitle files
    nums = set()
    for f in SUBS_DIR.glob("*.vtt"):
        m = re.match(r'^(\d+)-', f.name)
        if m:
            nums.add(int(m.group(1)))

    fixed = 0
    for num in sorted(nums):
        es_path = SUBS_DIR / f"{num:02d}-es.vtt"
        en_path = SUBS_DIR / f"{num:02d}-en.vtt"
        unk_path = SUBS_DIR / f"{num:02d}-unknown.vtt"

        # Fix unknown files
        if unk_path.exists():
            if es_path.exists() and not en_path.exists():
                # We already have es, so unknown is likely en
                lang = detect_language(unk_path)
                if lang == "es":
                    # Overwrite es if unknown is bigger (better quality?)
                    if unk_path.stat().st_size > es_path.stat().st_size:
                        unk_path.replace(es_path)
                        print(f"  [{num:02d}] Reemplazado es.vtt (mayor tamaño)")
                    else:
                        unk_path.unlink()
                        print(f"  [{num:02d}] Eliminado duplicado español")
                else:
                    unk_path.rename(en_path)
                    print(f"  [{num:02d}] Renombrado unknown → en.vtt")
                    fixed += 1
            elif not es_path.exists() and not en_path.exists():
                # Detect and rename
                lang = detect_language(unk_path)
                target = SUBS_DIR / f"{num:02d}-{lang}.vtt"
                unk_path.rename(target)
                print(f"  [{num:02d}] Renombrado unknown → {lang}.vtt")
                fixed += 1
            elif es_path.exists() and en_path.exists():
                unk_path.unlink()
                print(f"  [{num:02d}] Eliminado unknown (ya existen es+en)")

        # Update course_content.json with found paths
        lesson = content_by_num.get(num)
        if lesson is not None:
            if es_path.exists():
                lesson["subtitle_es"] = f"subtitles/{num:02d}-es.vtt"
            if en_path.exists():
                lesson["subtitle_en"] = f"subtitles/{num:02d}-en.vtt"

    # Save updated content
    CONTENT_FILE.write_text(
        json.dumps(content, ensure_ascii=False, indent=2),
        encoding="utf-8"
    )

    # Summary
    total_es = len(list(SUBS_DIR.glob("*-es.vtt")))
    total_en = len(list(SUBS_DIR.glob("*-en.vtt")))
    total_unk = len(list(SUBS_DIR.glob("*-unknown.vtt")))
    print(f"\nSubtítulos ES: {total_es} | EN: {total_en} | sin resolver: {total_unk}")
    print(f"Archivos renombrados: {fixed}")
    print("\nActualizando DB...")

    subprocess.run(["python", str(SCRIPTS_DIR / "build_course_map.py")], check=True)
    subprocess.run(
        ["php", "artisan", "raio:import", "--force"],
        cwd=str(BASE_DIR), check=True
    )
    print("\nListo. Subtítulos disponibles en el curso.")


if __name__ == "__main__":
    main()
