import http.client
import json

conn = http.client.HTTPSConnection("services.leadconnectorhq.com")

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer APIKEY',
    'Version': '2021-07-28'
}

location_id = "69jbeIj2NHqOyRqcklPo"
pipeline_id = "fxII6ro6lplz3xD0vjS7"
all_opps = []
search_after = []

while True:
    payload = json.dumps({
        "locationId": location_id,
        "query": "",
        "limit": 20,
        "page": 0,
        "searchAfter": search_after,
        "additionalDetails": {
            "notes": False,
            "tasks": False,
            "calendarEvents": False,
            "unReadConversations": True
        }
    })

    conn.request("POST", "/opportunities/search", payload, headers)
    res = conn.getresponse()
    data = res.read()
    resp_json = json.loads(data)

    opportunities = resp_json.get("opportunities", [])
    for opp in opportunities:
        if opp.get("pipelineId") == pipeline_id:
            all_opps.append({"id": opp["id"], "name": opp.get("name", "")})

    meta = resp_json.get("meta", {})
    start_after_id = meta.get("startAfterId")
    if not start_after_id:  # No more pages
        break

    search_after = [start_after_id]

print("Total opportunities fetched:", len(all_opps))
