#!/usr/bin/env python3
import json, time, urllib.request, urllib.parse, urllib.error

TOKEN = open("/opt/mia/config/meta_token_renato.txt").read().strip()
ACCT = "act_517468148842987"
PAGE_ID = "379331292096763"
PIXEL_ID = "464623303880507"
API = "v21.0"
BASE = f"https://graph.facebook.com/{API}"
CHECKOUT = "https://go.hotmart.com/J14755507D?src=ads07.26"
UTM = "utm_source=meta&utm_medium=cpc&utm_campaign=mesas-radionicas-07.26"
LINK = f"{CHECKOUT}&{UTM}"

IDS_FILE = "/opt/mia/workspace/clientes/borrello/campanha_mesas_ids.json"
ids = json.load(open(IDS_FILE))
videos = ids["videos"]
adsets = ids["adsets"]
ids.setdefault("creatives", {})
ids.setdefault("ads", {})

import json as _json
THUMBS = _json.load(open("/tmp/thumbs.json"))

TITLE = "Mesas Radiônicas Quânticas - Francisco Borrello"
MESSAGE = "Aprenda a trabalhar com 5 Mesas Radiônicas e transforme sua vida energeticamente."

# adset_key -> list of (mesa_name, tag)
PLAN = {
    "A_frio":     [("MESAS 1", "FRIO"), ("MESAS 2", "FRIO"), ("MESAS 3", "FRIO")],
    "B_quente":   [("MESAS 4", "QUENTE"), ("MESAS 5", "QUENTE")],
    "C_crosssell":[("MESAS 1", "CROSS"), ("MESAS 4", "CROSS")],
}

def post(path, payload):
    payload = dict(payload)
    payload["access_token"] = TOKEN
    data = urllib.parse.urlencode(payload).encode()
    req = urllib.request.Request(f"{BASE}/{path}", data=data, method="POST")
    try:
        r = urllib.request.urlopen(req)
        return True, json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        try:
            return False, json.loads(body)
        except Exception:
            return False, {"raw": body}

def err_info(resp):
    e = resp.get("error", {})
    return e.get("code"), e.get("error_subcode"), e.get("message"), e.get("error_user_title")

log = []
def L(msg):
    print(msg, flush=True)
    log.append(msg)

# ---------- STEP 1: creatives ----------
def make_creative(mesa_name, adset_tag, video_id):
    name = f"Creative {mesa_name} - AdSet {adset_tag}"
    spec = {
        "page_id": PAGE_ID,
        "video_data": {
            "video_id": video_id,
            "image_url": THUMBS[mesa_name],
            "title": TITLE,
            "message": MESSAGE,
            "call_to_action": {
                "type": "LEARN_MORE",
                "value": {"link": LINK},
            },
        },
    }
    payload = {"name": name, "object_story_spec": json.dumps(spec)}
    ok, resp = post(f"{ACCT}/adcreatives", payload)
    return ok, resp

# creative key = f"{mesa}|{tag}"
creative_ids = {}
for adset_key, items in PLAN.items():
    for mesa_name, tag in items:
        ckey = f"{mesa_name}|{tag}"
        if ckey in ids["creatives"]:
            creative_ids[ckey] = ids["creatives"][ckey]
            L(f"[skip] creative existente {ckey} -> {ids['creatives'][ckey]}")
            continue
        ok, resp = make_creative(mesa_name, tag, videos[mesa_name])
        if ok:
            cid = resp.get("id")
            creative_ids[ckey] = cid
            ids["creatives"][ckey] = cid
            L(f"[ok] creative {ckey} -> {cid}")
        else:
            code, sub, msg, title = err_info(resp)
            L(f"[FAIL creative] {ckey} code={code} subcode={sub} title={title} msg={msg}")
        time.sleep(1)

json.dump(ids, open(IDS_FILE, "w"), ensure_ascii=False, indent=2)

# ---------- STEP 2: ads (progressive fallback) ----------
def make_ad(name, adset_id, creative_id, attempt):
    payload = {
        "name": name,
        "adset_id": adset_id,
        "creative": json.dumps({"creative_id": creative_id}),
        "status": "PAUSED",
    }
    if attempt == 1:
        payload["tracking_specs"] = json.dumps(
            [{"action.type": ["offsite_conversion"], "fb_pixel": [PIXEL_ID]}]
        )
    # attempt 2: no tracking_specs (already PAUSED)
    ok, resp = post(f"{ACCT}/ads", payload)
    return ok, resp

for adset_key, items in PLAN.items():
    adset_id = adsets[adset_key]
    tag = items[0][1]
    for mesa_name, tag in items:
        ckey = f"{mesa_name}|{tag}"
        akey = f"{mesa_name}|{tag}|{adset_key}"
        if akey in ids["ads"]:
            L(f"[skip] ad existente {akey} -> {ids['ads'][akey]}")
            continue
        cid = creative_ids.get(ckey)
        if not cid:
            L(f"[skip] sem creative para {ckey}, pulando ad {akey}")
            continue
        ad_name = f"{mesa_name} [{tag}]"

        # attempt 1: with tracking_specs
        ok, resp = make_ad(ad_name, adset_id, cid, attempt=1)
        if ok:
            ids["ads"][akey] = resp.get("id")
            L(f"[ok attempt1] ad {akey} -> {resp.get('id')}")
            time.sleep(1)
            continue
        code, sub, msg, title = err_info(resp)
        L(f"[attempt1 fail] {akey} code={code} subcode={sub} title={title} msg={msg}")

        # attempt 2: no tracking_specs
        ok, resp = make_ad(ad_name, adset_id, cid, attempt=2)
        if ok:
            ids["ads"][akey] = resp.get("id")
            L(f"[ok attempt2 no-tracking] ad {akey} -> {resp.get('id')}")
            time.sleep(1)
            continue
        code, sub, msg, title = err_info(resp)
        L(f"[attempt2 fail] {akey} code={code} subcode={sub} title={title} msg={msg}")
        L(f"    >>> BLOQUEADOR: {json.dumps(resp.get('error', resp), ensure_ascii=False)}")
        time.sleep(1)

json.dump(ids, open(IDS_FILE, "w"), ensure_ascii=False, indent=2)

# summary
L("")
L(f"=== RESUMO ===")
L(f"creatives criados: {len(ids['creatives'])}")
L(f"ads criados: {len(ids['ads'])}")

open("/tmp/step3_log.txt", "w").write("\n".join(log))
