#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# /var/www/html/orchestrator.py

import json
import time
import importlib
import sys
from utils_hibrido import obter_conexao, registrar_log

sys.path.append('/var/www/html')

def carregar_config_sistema(cursor):
    """Carrega as configurações do banco."""
    try:
        cursor.execute("SELECT chave, valor FROM config_sistema")
        dados = cursor.fetchall()
        configs = {item['chave']: item['valor'] for item in dados}
        return configs
    except Exception as e:
        registrar_log('ORCHESTRATOR', f"Erro ao ler config_sistema: {str(e)}")
        return {}

def processar_job(conn, cursor, job):
    job_id = job['id']
    atendimento_id = job['atendimento_id']
    payload = json.loads(job['payload'])
    mensagem_bruta = payload.get('mensagem', '')
    
    configs = carregar_config_sistema(cursor)
    
    # Busca atendimento atualizado
    cursor.execute("""
        SELECT id, protocolo, cliente_numero, cliente_cpf, fluxo_atual, estado_atual, contexto_json, status
        FROM atendimentos WHERE id = %s
    """, (atendimento_id,))
    atendimento = cursor.fetchone()
    
    if not atendimento:
        registrar_log('ORCHESTRATOR', f"Atendimento {atendimento_id} não encontrado.")
        return
    
    # Converter para dict
    atendimento = dict(atendimento)
    
    # Roteamento dinâmico
    fluxo_nome = atendimento['fluxo_atual'].lower()
    modulo_nome = f"fluxo_{fluxo_nome}"
    
    try:
        modulo = importlib.import_module(modulo_nome)
        importlib.reload(modulo)
        modulo.processar(conn, cursor, job, atendimento, configs, mensagem_bruta)
    except ImportError:
        registrar_log('ORCHESTRATOR', f"Módulo {modulo_nome} não encontrado. Transferindo para humano.")
        from fluxo_humano import processar as humano_processar
        humano_processar(conn, cursor, job, atendimento, configs, mensagem_bruta)
    except Exception as e:
        registrar_log('ORCHESTRATOR', f"Erro em {modulo_nome}: {str(e)}")
    
    cursor.execute("UPDATE fila_robot SET processado = 1 WHERE id = %s", (job_id,))
    conn.commit()

def main():
    registrar_log('ORCHESTRATOR', "Orchestrator iniciado.")
    while True:
        try:
            conn = obter_conexao()
            cursor = conn.cursor(dictionary=True)
            cursor.execute("SELECT id, atendimento_id, payload FROM fila_robot WHERE processado = 0 ORDER BY id ASC LIMIT 1")
            job = cursor.fetchone()
            if job:
                processar_job(conn, cursor, job)
            cursor.close()
            conn.close()
        except Exception as e:
            registrar_log('ORCHESTRATOR', f"Erro no loop: {str(e)}")
        time.sleep(2)

if __name__ == '__main__':
    main()
