#!/usr/bin/env python3
# Processa os 46 artigos -> Buenas-New/src/blog-data.json + imagens + header/footer.
import json, re, os, shutil, hashlib, subprocess

RAW = "/private/tmp/claude-502/-Users-Bayerl-Documents-Projetos-Brandspace/92470cff-160a-4972-9480-ff3f55b779fd/scratchpad/blog-raw.json"
PROJ = "/Users/Bayerl/Documents/Projetos/Buenas-New"
UPLOADS = "/Users/Bayerl/Documents/Projetos/buenascarnes-local/site/wp-content/uploads"
BLOGDIR = os.path.join(PROJ, "public", "assets", "blog")
os.makedirs(BLOGDIR, exist_ok=True)

data = json.load(open(RAW))

def localize_img(url):
    if not url: return url
    m = re.search(r"/wp-content/uploads/(.+)$", url)
    if not m: return url
    rel = m.group(1).split("?")[0]
    src = os.path.join(UPLOADS, rel)
    if not os.path.exists(src):
        # tenta sem sufixo -NNNxNNN (thumbnail) -> original
        alt = re.sub(r"-\d+x\d+(\.\w+)$", r"\1", src)
        if os.path.exists(alt): src = alt
        else: return url
    base = re.sub(r"[^A-Za-z0-9._-]", "_", os.path.basename(rel))
    root, ext = os.path.splitext(base)
    h = hashlib.md5(url.encode()).hexdigest()[:8]
    out = "%s.%s%s" % (root, h, ext)
    dest = os.path.join(BLOGDIR, out)
    shutil.copy(src, dest)
    # otimiza (originais chegam a 20MB) -> max 1600px, qualidade 80
    try:
        subprocess.run(["sips", "-Z", "1600", "--setProperty", "formatOptions", "80", dest],
                       capture_output=True, timeout=40)
    except Exception:
        pass
    return "/assets/blog/" + out

def strip_html(h):
    t = re.sub(r"<[^>]+>", " ", h or "")
    t = re.sub(r"&[a-z]+;", " ", t)
    return re.sub(r"\s+", " ", t).strip()

articles = []
for a in data:
    content = a["content"] or ""
    # localiza imagens do conteudo
    content = re.sub(r'(<img[^>]*?\ssrc=")([^"]+)(")',
                     lambda m: m.group(1) + localize_img(m.group(2)) + m.group(3), content, flags=re.I)
    # remove artefatos do google translate
    content = re.sub(r'<[^>]*gtx-trans[^>]*>.*?</[^>]+>', '', content, flags=re.I | re.S)
    # remove titulo duplicado (primeiro heading == titulo) e converte "Subtítulo:" em lead
    _t = lambda s: re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", s or "")).strip()
    # o primeiro <h1> do conteúdo é sempre o título duplicado -> remove
    mh = re.match(r"\s*<h1[^>]*>.*?</h1>\s*", content, re.I | re.S)
    if mh:
        content = content[mh.end():]
    ms = re.match(r"\s*<h2[^>]*>(.*?)</h2>\s*", content, re.I | re.S)
    if ms and re.match(r"subt[íi]tulo\s*:", _t(ms.group(1)), re.I):
        lead = re.sub(r"^\s*subt[íi]tulo\s*:\s*", "", _t(ms.group(1)), flags=re.I)
        content = '<p class="bn-lead">%s</p>\n' % lead + content[ms.end():]
    excerpt = strip_html(content)[:180].rsplit(" ", 1)[0] + "…"
    articles.append({
        "slug": a["slug"],
        "title": a["title"],
        "date": a["date"],
        "excerpt": excerpt,
        "image": localize_img(a["img"]),
        "content": content,
    })

with open(os.path.join(PROJ, "src", "blog-data.json"), "w") as f:
    json.dump(articles, f, ensure_ascii=False)

# ---- extrai header e footer de uma pagina capturada (tag-balancing) ----
def extract_element(htmlstr, attr):
    i = htmlstr.find(attr)
    if i < 0: return ""
    start = htmlstr.rfind("<", 0, i)
    tagm = re.match(r"<([a-zA-Z0-9]+)", htmlstr[start:])
    if not tagm: return ""
    tag = tagm.group(1)
    depth = 0
    for m in re.finditer(r"<(/?)%s\b[^>]*?(/?)>" % re.escape(tag), htmlstr[start:], re.I):
        if m.group(2) == "/":  # self-closing
            if m.start() == 0: continue
        if m.group(1) == "/":
            depth -= 1
            if depth == 0:
                return htmlstr[start:start + m.end()]
        else:
            depth += 1
    return ""

body = open(os.path.join(PROJ, "src", "contato-body.html"), encoding="utf-8").read()
header = extract_element(body, 'data-elementor-type="header"')
footer = extract_element(body, 'data-elementor-type="footer"')
open(os.path.join(PROJ, "src", "_header.html"), "w").write(header)
open(os.path.join(PROJ, "src", "_footer.html"), "w").write(footer)

print("artigos:", len(articles))
print("header bytes:", len(header), "| footer bytes:", len(footer))
print("imagens no blog/:", len(os.listdir(BLOGDIR)))
print("exemplo:", articles[0]["title"][:40], "| img:", articles[0]["image"])
