import requests, json, time, csv

API_KEY = "apify_api_P3r95DNB3QjDySjpUWrFPQzVKvKNOO09xnav"
ACTOR_ID = "compass~crawler-google-places"

# Use searchStringsArray as an array (as per API docs)
payload = {
    "searchStringsArray": ["commercial cleaning companies"],
    "locationQuery": "Denver, Colorado, USA",
    "maxCrawledPlaces": 100,
    "language": "en"
}

print("Payload:", json.dumps(payload))

run_resp = requests.post(
    f"https://api.apify.com/v2/acts/{ACTOR_ID}/runs?token={API_KEY}",
    json={"input": payload}
).json()

print("Run response:", json.dumps(run_resp, indent=2))

if "data" not in run_resp:
    print("Error starting run:", run_resp)
    exit(1)

run_id = run_resp["data"]["id"]
dataset_id = run_resp["data"]["defaultDatasetId"]
print(f"Run ID: {run_id}")

# Wait for completion
for i in range(40):  # max 10 minutes
    r = requests.get(f"https://api.apify.com/v2/actor-runs/{run_id}?token={API_KEY}").json()
    status = r["data"]["status"]
    print(f"Status: {status}")
    if status in ["SUCCEEDED", "FAILED", "ABORTED"]:
        break
    time.sleep(15)

# Get results
items = requests.get(
    f"https://api.apify.com/v2/datasets/{dataset_id}/items?token={API_KEY}&format=json&clean=true"
).json()

print(f"Got {len(items)} places")

# Save to correct path
with open("/data/openclaw/leads/raw/denver-2026-03-12.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["business_name", "phone", "website", "address", "rating", "review_count", "category", "scrape_date"])
    w.writeheader()
    for item in items:
        w.writerow({
            "business_name": item.get("title", ""),
            "phone": item.get("phone", ""),
            "website": item.get("website", ""),
            "address": item.get("address", ""),
            "rating": item.get("totalScore", ""),
            "review_count": item.get("reviewsCount", ""),
            "category": item.get("categoryName", ""),
            "scrape_date": "2026-03-12"
        })

print("Done. Saved to /data/openclaw/leads/raw/denver-2026-03-12.csv")

# Show sample
if items:
    print("\n--- Sample (first 5) ---")
    for item in items[:5]:
        print(f"  {item.get('title')} - {item.get('phone')} - {item.get('totalScore')} stars")
