"""
Rename executor - Copies files to analyzed_samples/ with standardized names.
Reads from data/rename_plan.json generated by the batch analyzer.
"""
from __future__ import annotations

import sys
import os
import json
import shutil
import warnings

warnings.filterwarnings("ignore")

PROJECT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.chdir(PROJECT)
if PROJECT not in sys.path:
    sys.path.insert(0, PROJECT)

from src.analyzer import plan_renames, execute_renames


def main():
    rename_path = os.path.join(PROJECT, "data", "rename_plan.json")
    index_path = os.path.join(PROJECT, "data", "sample_index.json")
    output_dir = os.path.join(PROJECT, "librerias", "analyzed_samples")

    # Load rename plan if exists, otherwise generate from index
    if os.path.exists(rename_path):
        print("Cargando plan de renombrado existente...")
        with open(rename_path, "r", encoding="utf-8") as f:
            renames = json.load(f)
    elif os.path.exists(index_path):
        print("Generando plan desde indice...")
        with open(index_path, "r", encoding="utf-8") as f:
            index = json.load(f)
        renames = plan_renames(index["samples"], output_dir)
        with open(rename_path, "w", encoding="utf-8") as f:
            json.dump(renames, f, ensure_ascii=False, indent=2)
    else:
        print("ERROR: No existe data/sample_index.json ni data/rename_plan.json")
        print("       Ejecuta primero 1_ANALIZAR.bat")
        return

    print(f"\n{len(renames)} archivos para renombrar")
    print(f"Destino: {output_dir}")
    print()

    # Show sample renames
    print("Ejemplos:")
    for r in renames[:15]:
        print(f"  {r['original_name']:50s} -> {r['role']:10s}\\{r['new_name']}")
    if len(renames) > 15:
        print(f"  ... y {len(renames) - 15} mas")
    print()

    # Confirm
    answer = input("Ejecutar renombrado? (s/n): ").strip().lower()
    if answer != "s":
        print("Cancelado.")
        return

    # Execute
    print("\nCopiando archivos...")
    stats = execute_renames(renames, dry_run=False)

    print(f"\nResultado: {stats['executed']} copiados, {stats['skipped']} omitidos, {len(stats.get('errors', []))} errores")

    if stats.get("errors"):
        print("Errores:")
        for e in stats["errors"][:10]:
            print(f"  {e}")

    # Save rename log
    log_path = os.path.join(PROJECT, "data", "rename_log.json")
    with open(log_path, "w", encoding="utf-8") as f:
        json.dump({"stats": stats, "renames": renames}, f, ensure_ascii=False, indent=2)
    print(f"\nLog guardado en: {log_path}")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"\nFATAL ERROR: {e}")
        import traceback
        traceback.print_exc()
        input("Presiona Enter para cerrar...")
