import os, requests, time
TP_KEY = os.environ["TRUSTPILOT_API_KEY"]
MV = os.environ["MAVERA_API_KEY"]
BU_ID = os.environ["TRUSTPILOT_BU_ID"]
TP_BASE = "https://api.trustpilot.com/v1"
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
# 1. Current TrustScore
bu = requests.get(f"{TP_BASE}/business-units/{BU_ID}",
params={"apikey": TP_KEY}).json()
current_score = bu.get("score", {}).get("trustScore", 0)
review_count = bu.get("numberOfReviews", {}).get("total", 0)
star_dist = bu.get("score", {}).get("stars", {})
BASELINE_SCORE = 4.5
print(f"Current TrustScore: {current_score} (baseline: {BASELINE_SCORE})")
print(f"Total reviews: {review_count}")
print(f"Star distribution: {star_dist}")
# 2. If score dropped, pull recent negative reviews
if current_score < BASELINE_SCORE:
drop = BASELINE_SCORE - current_score
print(f"\n⚠ Score dropped by {drop:.1f} points")
negative_reviews = []
for stars in [1, 2, 3]:
r = requests.get(f"{TP_BASE}/business-units/{BU_ID}/reviews",
params={"apikey": TP_KEY, "stars": stars, "perPage": 20,
"orderBy": "createdat.desc"})
r.raise_for_status()
negative_reviews.extend(r.json().get("reviews", []))
time.sleep(0.2)
# 3. Build review block for analysis
review_block = "\n\n".join(
f"[{r.get('stars',0)}★] {r.get('title','No title')}\n{r.get('text','')[:300]}\nDate: {r.get('createdAt','')[:10]}"
for r in negative_reviews[:20]
)
# 4. Mave root cause analysis
analysis = requests.post("https://app.mavera.io/api/v1/mave/chat",
headers=MV_H,
json={"message": f"""Our Trustpilot TrustScore dropped from {BASELINE_SCORE} to {current_score}.
Total reviews: {review_count}. Star distribution: {star_dist}.
Recent negative reviews:
{review_block}
Analyze:
1. Root causes — what themes drive negative reviews?
2. Frequency — which issues appear most?
3. Severity — which issues cause 1-star vs 3-star?
4. Trend — are issues getting worse or improving?
5. Actionable fixes — what operational changes would address each root cause?
6. Response strategy — how to reply to each theme category"""}).json()
print("\n=== Root Cause Analysis ===")
print(analysis.get("content", "")[:1500])
# 5. Generate response templates
gen = requests.post("https://app.mavera.io/api/v1/generations",
headers=MV_H,
json={"prompt": f"""Based on this root cause analysis, generate 4 review response templates:
{analysis.get('content','')[:1000]}
For each template:
- Category name (e.g., "Shipping Delay", "Product Quality")
- Tone: empathetic, solution-oriented, professional
- Acknowledge the specific issue
- Offer a concrete next step
- Keep under 100 words each
- Never use corporate jargon"""}).json()
print("\n=== Response Templates ===")
print(gen.get("output", gen.get("content", gen.get("text", "")))[:1200])
else:
print(f"✓ Score stable at {current_score}")