import json, ast, io, urllib.request, urllib.error

# Le API/KEY do script da NF PMO SEM importar o modulo: o import executa o
# deploy dele (o arquivo nao tem guarda __main__).
_src = io.open('/home/ultimo/nf-pmo/deploy_workflow.py', encoding='utf-8').read()
_const = {}
for _n in ast.parse(_src).body:
    if isinstance(_n, ast.Assign) and isinstance(_n.value, ast.Constant):
        for _t in _n.targets:
            if isinstance(_t, ast.Name) and _t.id in ('API', 'KEY'):
                _const[_t.id] = _n.value.value
API, KEY = _const['API'], _const['KEY']

WF = 'R1zn1l8zDaVpFSkm'
NODE = 'Extrair Dados da Matéria'
SETTINGS_OK = {'saveExecutionProgress', 'saveManualExecutions', 'saveDataErrorExecution',
               'saveDataSuccessExecution', 'executionTimeout', 'errorWorkflow',
               'timezone', 'executionOrder'}

ERRO_ANTES = "($json.error?.message || $json.message || JSON.stringify($json)).substring(0, 300)"
ERRO_DEPOIS = ("(typeof $json.error === 'string' ? $json.error "
               ": ($json.error?.message || $json.message || JSON.stringify($json))).substring(0, 350)")


def call(metodo, caminho, corpo=None):
    req = urllib.request.Request(
        API + caminho, method=metodo,
        data=json.dumps(corpo).encode() if corpo else None,
        headers={'X-N8N-API-KEY': KEY, 'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        print('HTTP', e.code, e.read().decode()[:400])
        raise


wf = call('GET', '/workflows/' + WF)
print('ativo:', wf.get('active'))

novo_code = io.open('/tmp/extrair_dados_NOVO.js', encoding='utf-8').read()

for n in wf['nodes']:
    if n['name'] == NODE:
        n['parameters']['jsCode'] = novo_code
        n['onError'] = 'continueErrorOutput'
    if n['name'] == 'Telegram - Erro':
        jb = n['parameters']['jsonBody']
        if ERRO_ANTES in jb:
            n['parameters']['jsonBody'] = jb.replace(ERRO_ANTES, ERRO_DEPOIS, 1)
            print('mensagem do Telegram - Erro atualizada')
        elif ERRO_DEPOIS in jb:
            print('mensagem do Telegram - Erro ja estava atualizada')
        else:
            print('ATENCAO: trecho da mensagem nao encontrado, nada alterado nele')

wf['connections'][NODE]['main'] = [
    [{'node': 'OpenAI - Gerar Textos', 'type': 'main', 'index': 0}],
    [{'node': 'Telegram - Erro', 'type': 'main', 'index': 0}],
]

call('PUT', '/workflows/' + WF, {
    'name': wf['name'],
    'nodes': wf['nodes'],
    'connections': wf['connections'],
    'settings': {k: v for k, v in (wf.get('settings') or {}).items() if k in SETTINGS_OK},
})
print('PUT ok')

dep = call('GET', '/workflows/' + WF)
node = [n for n in dep['nodes'] if n['name'] == NODE][0]
tg = [n for n in dep['nodes'] if n['name'] == 'Telegram - Erro'][0]
print('ativo depois:', dep.get('active'), '| onError:', node.get('onError'))
print('guardas no codigo:', 'GUARDA 1' in node['parameters']['jsCode'],
      'GUARDA 2' in node['parameters']['jsCode'])
print('sem dois-pontos no throw:', 'endereco mudou. ' in node['parameters']['jsCode'])
print('telegram le string:', "typeof $json.error === 'string'" in tg['parameters']['jsonBody'])
