import os import argparse from datetime import datetime, timezone from supabase import create_client, Client # Connect to Supabase url = os.environ["SUPABASE_URL"] key = os.environ["SUPABASE_SERVICE_KEY"] supabase: Client = create_client(url, key) def send_thanks(limit=25, dry_run=False): # Fetch up to `limit` queued thank-yous rows = supabase.table("v_thanks_queue").select("*").eq("thanks_needed", True).limit(limit).execute().data sent, skipped, errors = 0, 0, 0 for r in rows: first_name = r.get("first_name") or "there" message = ( f"Hi {first_name}, it’s Lia at Lincoln Audi β€” thanks for popping in today. " "If any questions come up or you want to tweak the options we discussed, just message me here. " "Appreciate your time!" ) if dry_run: print(f"[DRY-RUN] Would message: {first_name} ({r['agreement_number']})") skipped += 1 continue try: # Insert into contact_history supabase.table("contact_history").insert({ "agreement_id": r["agreement_id"], "direction": "outbound", "channel": "whatsapp", "message_text": message, "intent_label": "thanks_followup", "template_slug": "thanks_followup", "source": "ai" }).execute() # Update appointment_request to mark thank-you sent supabase.table("appointment_request").update({ "thanks_needed": False, "thanks_sent_at": datetime.now(timezone.utc).isoformat() }).eq("id", r["appt_id"]).execute() print(f"βœ… Sent thank-you to {first_name} ({r['agreement_number']})") sent += 1 except Exception as e: print(f"❌ Error sending to {r['agreement_number']}: {e}") errors += 1 print(f"\nSummary: Sent={sent}, Skipped={skipped}, Errors={errors}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Send thank-you messages for attended appointments") parser.add_argument("--limit", type=int, default=25) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() send_thanks(limit=args.limit, dry_run=args.dry_run)