#!/usr/bin/env python3
# Gera contacts_overlay/{id}.json a partir do CSV RADIOSNET (col 0 = id venganet).
# peru.php mescla por cima do feed -> preenche o que o venganet nao tem hoje.
# Uso: python3 build_overlay_from_csv.py "RADIOSNET 2025 - RADIOSNET.csv"
import csv, json, os, re, sys, datetime

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, "contacts_overlay"); os.makedirs(OUT, exist_ok=True)
FEED = {f[:-5] for f in os.listdir(os.path.join(BASE, "radio")) if f.endswith(".json")}

# coluna -> (tipo, token exigido no valor: "@"=email, "#"=telefone, ""=url qualquer, resto=dominio)
COLS = {4:("site",""), 5:("email","@"), 13:("phone","#"), 14:("whatsapp","#"),
        16:("youtube","you"), 18:("tiktok","tiktok"), 19:("telegram","t.me"),
        20:("soundcloud","soundcloud"), 21:("twitter","twitt"),
        22:("facebook","faceb"), 23:("instagram","instag")}
DATE = re.compile(r"\d{1,2}[/:]\d")  # pega data 13/05/2025 e hora 13:23

def norm(v):
    d = re.sub(r"\D", "", v)
    if d.startswith("510"): return "51" + d[3:]   # tira o 0 do tronco
    return d if d.startswith("51") else "51" + d

def clean(tok, v):
    v = v.strip()
    if not v or v in "-—" or DATE.search(v): return None
    if tok == "@":  return v if "@" in v and " " not in v else None
    if tok == "#":  return norm(v) if sum(c.isdigit() for c in v) >= 8 and not re.search(r"[A-Za-z]", v) else None
    if tok == "":   return v if v.lower().startswith("http") else None
    return v if tok in v.lower() else None        # social: dominio tem que bater

wrote = 0
for row in csv.reader(open(sys.argv[1], newline="", encoding="utf-8", errors="replace")):
    if not row or not row[0].strip().isdigit() or row[0].strip() not in FEED:
        continue
    cont = []
    for i, (typ, tok) in COLS.items():
        val = clean(tok, row[i]) if i < len(row) else None
        if val: cont.append({"type": typ, "value": val})
    if not cont: continue
    rid = row[0].strip()
    json.dump({"id": int(rid), "title": row[1].strip(), "source": "RADIOSNET CSV 2025",
               "updated_at": str(datetime.date.today()), "contatos": cont},
              open(os.path.join(OUT, rid + ".json"), "w"), ensure_ascii=False, indent=1)
    wrote += 1
print("overlays gravados:", wrote)
