import os, requests, time
from datetime import datetime, timedelta
AH = os.environ["AHREFS_API_TOKEN"]
MV = os.environ["MAVERA_API_KEY"]
MB, TOPIC = "https://app.mavera.io/api/v1", "AI content marketing"
AH_H = {"Authorization": f"Bearer {AH}", "Accept": "application/json"}
MH = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
cutoff = (datetime.utcnow() - timedelta(days=90)).strftime("%Y-%m-%d")
resp = requests.get("https://api.ahrefs.com/v3/content-explorer/search", headers=AH_H, params={
"query": TOPIC, "mode": "title", "limit": 100,
"order_by": "referring_domains:desc",
"select": "title,url,published_at,organic_traffic,referring_domains,facebook_shares",
})
resp.raise_for_status()
articles = resp.json().get("articles", [])
trending = sorted(
[a for a in articles if a.get("published_at", "") >= cutoff
and (a.get("referring_domains", 0) >= 5 or a.get("facebook_shares", 0) >= 50)],
key=lambda a: a.get("referring_domains", 0), reverse=True)
print(f"Found {len(trending)} trending articles for '{TOPIC}'\n")
personas = []
for seg in ["B2B SaaS content manager", "freelance SEO consultant", "VP Marketing"]:
p = requests.post(f"{MB}/personas", headers=MH, json={
"name": f"Reader: {seg}",
"description": f"Searches '{TOPIC}'. Engages with high-share content. Role: {seg}.",
}).json()
personas.append(p["id"])
time.sleep(0.3)
concepts = [f"'{a['title']}' — {a.get('referring_domains', 0)} sites linked"
for a in trending[:5]]
fg = requests.post(f"{MB}/focus-groups", headers=MH, json={
"name": f"Trending: {TOPIC}", "persona_ids": personas,
"questions": [
"Which angle first?\n" + "\n".join(f"{i+1}. {c}" for i, c in enumerate(concepts)),
"What's missing from current coverage of this topic?",
"Would you share this with your team? Why or why not?",
], "responses_per_persona": 2,
}).json()
for _ in range(30):
time.sleep(5)
data = requests.get(f"{MB}/focus-groups/{fg['id']}", headers=MH).json()
if data.get("status") == "completed": break
for r in data.get("responses", [])[:9]:
print(f"[{r.get('persona_id', '?')}] {r.get('answer', '')[:300]}\n")