import os, requests
from collections import Counter
SF = os.environ["SALESFORCE_INSTANCE"]
SF_T = os.environ["SALESFORCE_ACCESS_TOKEN"]
MV_K = os.environ["MAVERA_API_KEY"]
SF_H = {"Authorization": f"Bearer {SF_T}"}
MV_H = {"Authorization": f"Bearer {MV_K}", "Content-Type": "application/json"}
opps = requests.get(
f"https://{SF}/services/data/v66.0/query", headers=SF_H,
params={"q": "SELECT StageName, Industry, Amount FROM Opportunity WHERE IsClosed = false ORDER BY Amount DESC LIMIT 100"},
).json()["records"]
seg_counts = Counter((o.get("StageName", "Unknown"), o.get("Industry", "Unknown")) for o in opps)
top_segments = seg_counts.most_common(5)
for (stage, industry), count in top_segments:
seg_value = sum(o.get("Amount", 0) for o in opps if o.get("StageName") == stage and o.get("Industry") == industry)
context = f"{count} open deals in '{stage}' stage, {industry} industry. Pipeline value: ${seg_value:,.0f}."
gen = requests.post(
"https://app.mavera.io/api/v1/generations", headers=MV_H,
json={
"input_data": context,
"prompt": (
f"Generate a nurture email for prospects in the '{stage}' stage, "
f"{industry} industry. Address common concerns at this stage, "
f"provide social proof, include a clear next-step CTA."
),
},
).json()
print(f"\n{'='*50}")
print(f"Stage: {stage} | Industry: {industry} | Deals: {count}")
print(f"{'='*50}")
print(gen.get("output", ""))