import os
import time
import threading
from .logger_utils import setup_global_logging, log_msg as log
from .settings import load_settings

# --- NUOVO IMPORT ---
from .train_executor import run_train_monitor

def build_info() -> str:
    return "core-orchestrator-v1.4-background-train"

def run_all_modes(settings):
    """Lancia in simultanea i processi core: Collect, Infer e il nuovo Train Executor."""
    log("Avvio modalitÃ  SIMULTANEA (Collect + Train Executor + Infer)...")
    
    # 1. Importiamo le funzioni dai rispettivi moduli
    from .train_collect import run_collect_train
    from .infer_mode import run_infer

    # 2. Thread per la RACCOLTA DATI (Collect)
    t_collect = threading.Thread(target=run_collect_train, args=(settings,), name="CollectorThread", daemon=True)
    
    # 3. Thread per il MONITOR ADDESTRAMENTO (Train Executor)
    # Rileva i file .lock inviati dal Web e addestra il modello in background
    t_train_exec = threading.Thread(target=run_train_monitor, name="TrainExecutorThread", daemon=True)

    # 4. Thread per l'INFERENZA (Predict)
    t_infer = threading.Thread(target=run_infer, args=(settings,), name="InferenceThread", daemon=True)

    # Avvio di tutti i processi in parallelo
    t_collect.start()
    t_train_exec.start()
    t_infer.start()

    log("Tutti i processi core (incluso Train Executor) sono attivi.")
    
    # Mantieni il main process attivo
    while True:
        time.sleep(10)

def main() -> None:
    # Fix percorsi configurazione
    if not os.environ.get("CONFIG"):
        os.environ["CONFIG"] = "/config/config.yaml"

    try:
        settings = load_settings()
        setup_global_logging(settings)
        log(f"Core Orchestrator avviato. BUILD: {build_info()}")
        
        mode = str(settings.get("mode", "all")).strip().lower()

        if mode == "all":
            run_all_modes(settings)
        elif mode == "collect_train":
            from .train_collect import run_collect_train
            run_collect_train(settings)
        elif mode == "infer":
            from .infer_mode import run_infer
            run_infer(settings)
        elif mode == "train":
            # Questa rimane la vecchia modalitÃ  manuale one-shot
            from .train_mode import run_train
            run_train(settings)
        else:
            log(f"ModalitÃ  {mode} non riconosciuta.")
            
    except Exception as e:
        print(f"ERRORE CRITICO ALL'AVVIO: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
