import os, requests, time
from collections import defaultdict
G2 = os.environ["G2_API_KEY"]
MV = os.environ["MAVERA_API_KEY"]
G2_BASE = "https://data.g2.com/api/v1"
G2_H = {"Authorization": f"Token token={G2}", "Content-Type": "application/vnd.api+json"}
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
COMPETITORS = [
{"name": "CompetitorA", "product_id": "competitor-a-product-id"},
{"name": "CompetitorB", "product_id": "competitor-b-product-id"},
]
all_intel = []
for comp in COMPETITORS:
reviews = []
page = 1
while len(reviews) < 100:
r = requests.get(f"{G2_BASE}/survey-responses",
headers=G2_H,
params={
"filter[product_id]": comp["product_id"],
"page[size]": 50,
"page[number]": page,
})
if r.status_code == 429:
time.sleep(1)
continue
r.raise_for_status()
data = r.json().get("data", [])
if not data:
break
reviews.extend(data)
page += 1
time.sleep(0.1)
loves, hates, recs = [], [], []
stars = []
for rev in reviews:
attrs = rev.get("attributes", {})
stars.append(attrs.get("star_rating", 0))
for key, val in attrs.get("comment_answers", {}).items():
text = val if isinstance(val, str) else val.get("text", "")
k = key.lower()
if "love" in k or "best" in k:
loves.append(text[:200])
elif "dislike" in k or "hate" in k:
hates.append(text[:200])
elif "recommend" in k:
recs.append(text[:200])
avg = sum(stars) / len(stars) if stars else 0
all_intel.append({
"name": comp["name"],
"review_count": len(reviews),
"avg_rating": round(avg, 1),
"top_loves": loves[:10],
"top_hates": hates[:10],
"recommendations": recs[:5],
})
# Build analysis prompt
intel_block = ""
for ci in all_intel:
intel_block += f"\n## {ci['name']} ({ci['review_count']} reviews, avg {ci['avg_rating']}/5)\n"
intel_block += f"LOVE:\n" + "\n".join(f"- {l}" for l in ci["top_loves"][:5]) + "\n"
intel_block += f"HATE:\n" + "\n".join(f"- {h}" for h in ci["top_hates"][:5]) + "\n"
intel_block += f"RECOMMENDATIONS:\n" + "\n".join(f"- {r}" for r in ci["recommendations"][:3]) + "\n"
analysis = requests.post("https://app.mavera.io/api/v1/mave/chat",
headers=MV_H,
json={"message": f"""Analyze these G2 competitor reviews and identify positioning opportunities for us.
{intel_block}
Produce:
1. Each competitor's core strengths (where they're hard to beat)
2. Each competitor's vulnerabilities (where their users are frustrated)
3. Positioning opportunities (where we can win based on their weaknesses)
4. Messaging angles (specific claims we can make that competitors can't)
5. Feature gaps (what their users want that we could build/highlight)
6. Risk areas (where competitors are improving — watch list)"""}).json()
print("=== Competitive Intelligence from G2 ===")
print(analysis.get("content", "")[:2000])