import json, urllib.request, urllib.parse
API="http://127.0.0.1:5678/api/v1"
KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI3ZmRmYzg1ZC1iNWNiLTQxMWItOTJhZC01MGNkMmNjYmFkMTEiLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwianRpIjoiZDJjOGY2N2ItNmFmMi00ZmQ1LWE0YTYtZjkzZjAyNTVlN2Y5IiwiaWF0IjoxNzc1ODM2MDM2fQ.8NbeIvPo3wSOXGkOwm0Oey-OV24oZ57oqpNHtdZjycQ"
CRED={"gmailOAuth2":{"id":"JrDIhubWWqvyxQA7","name":"Gmail account"}}

CANDIDATAS = {
 "A": 'in:sent subject:"NF Publicidade PMO" has:attachment',
 "B": 'from:ultimocampos@gmail.com subject:"NF Publicidade PMO" has:attachment',
 "C": 'in:sent "NF Publicidade PMO" has:attachment to:protocolo@oeiras.pi.gov.br',
}

def http(nome,q,pos):
    url=("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=2&q="
         + urllib.parse.quote(q))
    return {"parameters":{"url":url,"authentication":"predefinedCredentialType",
            "nodeCredentialType":"gmailOAuth2","options":{}},
            "id":nome,"name":nome,"type":"n8n-nodes-base.httpRequest",
            "typeVersion":4.2,"position":pos,"credentials":CRED}

JUNTAR = r"""
const r = {};
for (const nome of ['A','B','C']) {
  const d = $(nome).first().json;
  r[nome] = { total: d.resultSizeEstimate ?? 0, primeiro: (d.messages||[])[0]?.id || null };
}
return [{ json: r }];
"""

nodes=[{"parameters":{"httpMethod":"GET","path":"diag2","responseMode":"lastNode","options":{}},
        "id":"wh","name":"Start","type":"n8n-nodes-base.webhook","typeVersion":2,
        "position":[0,0],"webhookId":"diag2-nf"}]
prev="Start"; x=200
conns={}
for k,q in CANDIDATAS.items():
    nodes.append(http(k,q,[x,0]))
    conns[prev]={"main":[[{"node":k,"type":"main","index":0}]]}
    prev=k; x+=200
nodes.append({"parameters":{"jsCode":JUNTAR},"id":"j","name":"Juntar",
              "type":"n8n-nodes-base.code","typeVersion":2,"position":[x,0]})
conns[prev]={"main":[[{"node":"Juntar","type":"main","index":0}]]}

def api(m,p,b=None):
    r=urllib.request.Request(API+p,method=m,data=json.dumps(b).encode() if b else None,
        headers={"X-N8N-API-KEY":KEY,"Content-Type":"application/json"})
    try:
        with urllib.request.urlopen(r,timeout=30) as z: return json.loads(z.read() or "{}")
    except urllib.error.HTTPError as e: return {"erro":e.code,"detalhe":e.read().decode()[:300]}

for w in api("GET","/workflows?limit=100").get("data",[]):
    if w["name"]=="DIAG2": api("DELETE","/workflows/"+w["id"])
r=api("POST","/workflows",{"name":"DIAG2","nodes":nodes,"connections":conns,
      "settings":{"executionOrder":"v1"}})
if "id" in r: api("POST",f"/workflows/{r['id']}/activate"); print("ok")
else: print("falhou", r)
