#!/usr/bin/env python3
import os
import sys
import json
import subprocess

# --- COLORES ---
GREEN = '\033[0;32m'
BLUE = '\033[0;34m'
YELLOW = '\033[1;33m'
RED = '\033[0;31m'
NC = '\033[0m'

def find_engine():
    """Busca el directorio .ocr-indexer subiendo por el árbol de carpetas."""
    curr_dir = os.getcwd()
    while curr_dir != '/':
        engine_path = os.path.join(curr_dir, '.ocr-indexer')
        if os.path.isdir(engine_path):
            return engine_path
        curr_dir = os.path.dirname(curr_dir)
    return None

def mostrar_help():
    print(f"{BLUE}===================================================={NC}")
    print(f"{YELLOW}       SISTEMA OCR - CONTROL DE MOTORES LOCALES (PyPI) {NC}")
    print(f"{BLUE}===================================================={NC}")
    print(f"Uso: {GREEN}ocr-indexer [comando]{NC}\n")
    print(f"{YELLOW}--- GESTIÓN DE MOTOR ---{NC}")
    print(f"  {GREEN}dir{NC}             Crea un motor local en la carpeta actual.")
    print(f"  {GREEN}start / stop{NC}    Controla el indexador de esta carpeta.")
    print(f"  {GREEN}status / logs{NC}   Monitorea el progreso local.")
    print(f"  {GREEN}search{NC}          Busca texto en este motor.")
    print(f"  {GREEN}stats{NC}           Estadísticas de archivos.")
    print(f"  {GREEN}reset{NC}           Borra el índice local (con confirmación).\n")
    print(f"{YELLOW}--- GESTIÓN DE LISTA NEGRA ---{NC}")
    print(f"  {GREEN}blacklist-list{NC}   Muestra carpetas ignoradas.")
    print(f"  {GREEN}blacklist-add{NC}    Añade carpeta a ignorar.")
    print(f"  {GREEN}blacklist-rm{NC}     Quita carpeta de la lista negra.\n")
    print(f"{BLUE}----------------------------------------------------{NC}")

def main():
    args = sys.argv[1:]
    comando = args[0] if args else "help"

    # Rutas dinámicas para que encuentre los scripts sin importar dónde se instale
    base_dir = os.path.dirname(__file__)
    script_indexer = os.path.join(base_dir, "indexer.py")
    script_searcher = os.path.join(base_dir, "searcher.py")

    engine = find_engine()

    if comando == "dir":
        target = args[1] if len(args) > 1 else os.getcwd()
        engine_path = os.path.join(target, '.ocr-indexer')
        if not os.path.exists(engine_path):
            os.makedirs(engine_path)
            
            with open(os.path.join(engine_path, 'config.json'), 'w') as f:
                json.dump({"root": target, "blacklist": ["Talk", "trashbin"]}, f, indent=4)
                
            with open(os.path.join(engine_path, 'index.json'), 'w') as f:
                json.dump({}, f)
                
            print(f"{GREEN}✅ Motor local creado en: {target}{NC}")
        else:
            print(f"{YELLOW}⚠️ El motor ya existe en: {target}{NC}")
        return

    if comando == "help":
        mostrar_help()
        if engine:
            print(f"💡 Motor activo en: {BLUE}{engine}{NC}")
        print(f"{BLUE}===================================================={NC}")
        return

    # Comandos que requieren un motor activo
    if not engine:
        print(f"{RED}❌ No se detectó ningún motor aquí. Usa 'ocr-indexer dir' primero.{NC}")
        return

    config_path = os.path.join(engine, 'config.json')
    index_path = os.path.join(engine, 'index.json')
    log_path = os.path.join(engine, 'indexer.log')

    if comando == "start":
        print(f"{GREEN}🚀 Iniciando indexador en background...{NC}")
        with open(log_path, 'a') as log_file:
            subprocess.Popen([sys.executable, "-u", script_indexer, engine], stdout=log_file, stderr=log_file)

    elif comando == "stop":
        subprocess.run(["pkill", "-f", engine])
        print(f"{RED}🛑 Proceso detenido.{NC}")

    elif comando == "status":
        print(f"{BLUE}--- ESTADO LOCAL ---{NC}")
        # Revisa si hay procesos corriendo que contengan la ruta del motor
        proc = subprocess.run(["pgrep", "-f", engine], capture_output=True, text=True)
        if proc.stdout.strip():
            print(f"Estado: {GREEN}CORRIENDO{NC}")
        else:
            print(f"Estado: {RED}DETENIDO{NC}")
        
        try:
            with open(index_path, 'r') as f:
                data = json.load(f)
            print(f"📂 Archivos indexados: {YELLOW}{len(data)}{NC}")
        except:
            print(f"📂 Archivos indexados: {YELLOW}0{NC}")

    elif comando == "search":
        subprocess.run([sys.executable, script_searcher, index_path])

    elif comando == "logs":
        subprocess.run(["tail", "-f", log_path])

    elif comando == "stats":
        print(f"{BLUE}--- ESTADÍSTICAS ---{NC}")
        try:
            with open(index_path, 'r') as f:
                data = json.load(f)
            stats = {}
            for item in data.values():
                ext = item.get("archivo", {}).get("extension", "unknown")
                stats[ext] = stats.get(ext, 0) + 1
            for k, v in stats.items():
                print(f" {k.upper()}: {v}")
        except:
            print(f"{YELLOW}No hay datos para mostrar.{NC}")

    elif comando == "reset":
        res = input("¿Borrar índice local? (s/n): ")
        if res.lower() == 's':
            subprocess.run(["pkill", "-f", engine])
            with open(index_path, 'w') as f:
                json.dump({}, f)
            print(f"{RED}♻️ Motor reseteado.{NC}")

    elif comando == "blacklist-list":
        try:
            with open(config_path, 'r') as f:
                print('\n'.join(json.load(f).get('blacklist', [])))
        except: pass

    elif comando == "blacklist-add":
        if len(args) > 1:
            with open(config_path, 'r+') as f:
                data = json.load(f)
                if args[1] not in data.get('blacklist', []):
                    data.setdefault('blacklist', []).append(args[1])
                    f.seek(0)
                    json.dump(data, f, indent=4)
                    f.truncate()
            print(f"{GREEN}✅ '{args[1]}' añadido a la lista negra.{NC}")

    elif comando == "blacklist-rm":
        if len(args) > 1:
            with open(config_path, 'r+') as f:
                data = json.load(f)
                if args[1] in data.get('blacklist', []):
                    data['blacklist'].remove(args[1])
                    f.seek(0)
                    json.dump(data, f, indent=4)
                    f.truncate()
            print(f"{YELLOW}🗑️ '{args[1]}' eliminado de la lista negra.{NC}")
    else:
        mostrar_help()

if __name__ == "__main__":
    main()
