# Create a test-mode campaign with three recipients and start it. Python 3.9+ with requests.
# Every request runs, so the script looks for its campaign by name first: running it again never
# creates a second campaign or starts one twice.
import json
import os
import sys

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
# Defaults to the test-mode Sample agent; set AGENT_ID to use your own agent.
agent_id = os.environ.get("AGENT_ID", "agent_1ZltiWzxrXmMprGD6q63")
name = os.environ.get("CAMPAIGN_NAME", "November renewals (test)")
if not os.environ.get("RELATIONSAI_API_KEY", "").startswith("rai_test_"):
    sys.exit("Run this example with a test key (rai_test_...): it calls the test-mode numbers +1202555010x.")
# Consent is recorded only when you set CONSENT_GRANTED=true. Do that only if your workspace requires
# consent and, for real people, only when they really agreed to be called.
consent = {"consent_granted": True} if os.environ.get("CONSENT_GRANTED") == "true" else {}
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['RELATIONSAI_API_KEY']}"


def api(method, path, body=None):
    r = session.request(method, f"{base}{path}", json=body, timeout=30)
    data = r.json()
    if not r.ok:
        err = data["error"]
        sys.exit(f"{method} {path}: {err['code']}: {err['message']} {json.dumps(err['details'])} (request {err['request_id']})")
    return r.status_code, data


# 0. Already created by an earlier run? (Newest first; one page is enough for this example.)
_, page = api("GET", "/campaigns?limit=100")
campaign = next((c for c in page["data"] if c["name"] == name), None)

if campaign is None:
    # 1. Recipients are contacts (an upsert is safe to repeat). Test numbers: answers, no answer, longer talk.
    contact_ids = []
    for phone in ["+12025550100", "+12025550101", "+12025550105"]:
        _, contact = api("POST", "/contacts/upsert", {"phone_number": phone, **consent})
        contact_ids.append(contact["id"])
    # 2. Create the campaign. It starts as a draft: nothing is dialled yet.
    _, campaign = api("POST", "/campaigns", {"name": name, "agent_id": agent_id, "concurrency_limit": 2, "contact_ids": contact_ids})
    print(f"Created {campaign['id']} status={campaign['status']} recipients={campaign['recipient_count']}")

# 3. Start it, but only a draft: starting a finished campaign again would call everyone again.
if campaign["status"] != "draft":
    print(f"Already {campaign['status']} {campaign['id']}: not starting it again")
    sys.exit(0)
status, started = api("POST", f"/campaigns/{campaign['id']}/start")
# 200: running. 202: started but not yet confirmed (it still shows running).
print(f"Started {started['id']} status={started['status']} ({status}) run={started['run_number']}")
print(f"Recipients that this run calls: {started['recipient_count']}")
