#!/usr/bin/env python3
# Poller do Instagram público (@buenascarnesepasta) — sem login do visitante.
# Pega os N últimos posts via web_profile_info, baixa as thumbs pra public/assets/instagram/
# (as URLs do scontent expiram, por isso self-hospedamos), e injeta o grid no sobre-nos-body.html
# entre os marcadores IG-GRID. Se o IG bloquear, mantém o último cache (degrada bonito).
import json, os, re, sys, urllib.request, html

USER = "buenascarnesepasta"
N = 6
PROJ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IMG_DIR = os.path.join(PROJ, "public", "assets", "instagram")
FEED_JSON = os.path.join(IMG_DIR, "feed.json")
BODY = os.path.join(PROJ, "src", "sobre-nos-body.html")
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/122.0 Safari/537.36")

def fetch(url, headers=None, binary=False):
    req = urllib.request.Request(url, headers=headers or {"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.read() if binary else r.read().decode("utf-8")

def get_posts():
    url = f"https://i.instagram.com/api/v1/users/web_profile_info/?username={USER}"
    data = json.loads(fetch(url, {"User-Agent": UA, "x-ig-app-id": "936619743392459", "Accept": "*/*"}))
    edges = data["data"]["user"]["edge_owner_to_timeline_media"]["edges"][:N]
    posts = []
    for e in edges:
        n = e["node"]
        cap = "".join(c["node"]["text"] for c in n.get("edge_media_to_caption", {}).get("edges", []))
        posts.append({
            "shortcode": n["shortcode"],
            "img": n.get("display_url"),
            "caption": cap.strip(),
            "permalink": f"https://www.instagram.com/p/{n['shortcode']}/",
        })
    return posts

def build_grid(feed):
    items = []
    for p in feed:
        alt = html.escape((p["caption"][:80] or "Post do Instagram do Buenas Carnes").replace("\n", " "), quote=True)
        items.append(
            f'<a class="bn-ig-item" href="{p["permalink"]}" target="_blank" rel="noopener" '
            f'aria-label="Ver post no Instagram">'
            f'<img loading="lazy" decoding="async" src="/assets/instagram/{p["shortcode"]}.jpg" alt="{alt}">'
            f'<span class="bn-ig-ov" aria-hidden="true">'
            f'<svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="#fff" stroke-width="2">'
            f'<rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4.2"/>'
            f'<circle cx="17.5" cy="6.5" r="1.2" fill="#fff" stroke="none"/></svg></span></a>')
    return ('<!--IG-GRID-START--><div class="bn-ig-grid">' + "".join(items) + "</div><!--IG-GRID-END-->")

def inject(grid_html):
    t = open(BODY, encoding="utf-8").read()
    if "<!--IG-GRID-START-->" in t:
        t = re.sub(r"<!--IG-GRID-START-->.*?<!--IG-GRID-END-->", grid_html, t, flags=re.S)
    else:
        # 1ª vez: injeta logo antes do rodapé, dentro da banda clara
        anchor = '<div data-elementor-type="footer" data-elementor-id="136"'
        t = t.replace(anchor, '<div class="bn-ig-wrap">' + grid_html + "</div>\n" + anchor, 1)
    # aponta o botão "Visitar" pro Instagram real (href="#")
    t = t.replace('<a class="elementor-button elementor-button-link elementor-size-sm" href="#">',
                  f'<a class="elementor-button elementor-button-link elementor-size-sm" '
                  f'href="https://www.instagram.com/{USER}/" target="_blank" rel="noopener">', 1)
    open(BODY, "w", encoding="utf-8").write(t)

def main():
    os.makedirs(IMG_DIR, exist_ok=True)
    try:
        posts = get_posts()
    except Exception as e:
        print("IG fetch falhou (%s) — mantendo cache anterior" % e)
        if not os.path.exists(FEED_JSON):
            sys.exit(1)
        posts = json.load(open(FEED_JSON, encoding="utf-8"))
    ok = []
    for p in posts:
        dst = os.path.join(IMG_DIR, p["shortcode"] + ".jpg")
        try:
            if p.get("img"):
                open(dst, "wb").write(fetch(p["img"], binary=True))
            if os.path.exists(dst):
                ok.append({k: p[k] for k in ("shortcode", "caption", "permalink")})
        except Exception as e:
            print("  thumb falhou %s: %s" % (p["shortcode"], e))
            if os.path.exists(dst):
                ok.append({k: p[k] for k in ("shortcode", "caption", "permalink")})
    if not ok:
        print("nenhuma imagem — abortando sem alterar"); sys.exit(1)
    json.dump(ok, open(FEED_JSON, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    inject(build_grid(ok))
    print("OK — %d posts no grid do Instagram" % len(ok))

if __name__ == "__main__":
    main()
