import os, requests
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}"}
def sf_q(soql):
return requests.get(f"https://{SF}/services/data/v66.0/query", headers=SF_H, params={"q": soql}).json()["records"]
aid = "0015e000001XyZa"
acct = sf_q(f"SELECT Name, Industry, AnnualRevenue, Health_Score__c, Contract_End_Date__c, NumberOfEmployees FROM Account WHERE Id = '{aid}'")[0]
cases = sf_q(f"SELECT CaseNumber, Subject, Status, Priority, Description FROM Case WHERE AccountId = '{aid}' ORDER BY CreatedDate DESC LIMIT 20")
acts = sf_q(f"SELECT Subject, Description, ActivityDate FROM Task WHERE AccountId = '{aid}' ORDER BY ActivityDate DESC LIMIT 15")
open_cases = [c for c in cases if c.get("Status") not in ("Closed", "Resolved")]
hi_pri = [c for c in cases if c.get("Priority") in ("High", "Critical")]
case_blk = "\n".join(f"- [{c.get('Priority','Normal')}] {c.get('Subject','N/A')} — {c.get('Status')}: {(c.get('Description') or '')[:120]}" for c in cases[:12])
act_blk = "\n".join(f"- [{a.get('ActivityDate','N/A')}] {a.get('Subject','')}: {(a.get('Description') or '')[:120]}" for a in acts)
prompt = f"""Prepare a QBR document for this customer.
ACCOUNT: {acct['Name']} | {acct.get('Industry','N/A')} | ${acct.get('AnnualRevenue','N/A')} | Health: {acct.get('Health_Score__c','N/A')}/100
Contract End: {acct.get('Contract_End_Date__c','N/A')} | Employees: {acct.get('NumberOfEmployees','N/A')}
CASES ({len(open_cases)} open, {len(hi_pri)} high-priority)
{case_blk}
RECENT ACTIVITY
{act_blk}
Generate: 1) Executive summary (health, risk, opportunity) 2) Key wins 3) Risk flags with mitigations 4) 8 tailored QBR questions 5) Expansion opportunities 6) 30-min agenda 7) Talk track for top support issue"""
qbr = requests.post(
"https://app.mavera.io/api/v1/mave/chat",
headers={"Authorization": f"Bearer {MV_K}", "Content-Type": "application/json"},
json={"message": prompt},
).json()
print("=== QBR Prep ===")
print(qbr.get("content", ""))
print(f"Sources: {len(qbr.get('sources', []))}")