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930"
H = {"Authorization": f"Bearer {TOKEN}", "Accept": "application/json"}
url = f"https://platform-api.webgains.com/auth/publishers/{PUBLISHER_ID}/campaigns/1622230/feeds/products"

# Try page param
print("=== Try page param ===")
for page in [0, 1, 2]:
    params = {"feedIds[]": [18588], "size": 5, "page": page}
    r = requests.get(url, headers=H, params=params, timeout=10)
    data = r.json()
    prods = data.get("data", [])
    ids = [p.get("id") for p in prods]
    print(f"  page={page}: ids={ids[:3]}")

# Try sort + offset
print("\n=== Try sort ===")
for sort in ["id", "title", "price", "createdAt"]:
    params = {"feedIds[]": [18588], "size": 3, "sort": sort, "order": "asc"}
    r = requests.get(url, headers=H, params=params, timeout=10)
    data = r.json()
    prods = data.get("data", [])
    if prods:
        print(f"  sort={sort}: {prods[0].get('id')} | {prods[0].get('title','')[:40]}")

# Try max size
print("\n=== Try large size ===")
for sz in [2000, 5000, 10000]:
    params = {"feedIds[]": [18588], "size": sz}
    r = requests.get(url, headers=H, params=params, timeout=60)
    data = r.json()
    prods = data.get("data", [])
    unique_ids = len(set(p.get("id") for p in prods))
    print(f"  size={sz}: got {len(prods)} products, {unique_ids} unique IDs")
    if prods:
        # Check if all from baskets
        links = [p.get("link","") for p in prods[-3:]]
        baskets_count = sum(1 for l in links if "baskets" in l.lower() or "299740" in l)
        print(f"    Last 3 links are baskets: {baskets_count}/3")

# Try cursor/after param
print("\n=== Try cursor ===")
params = {"feedIds[]": [18588], "size": 5}
r = requests.get(url, headers=H, params=params, timeout=10)
data = r.json()
# Check for cursor/next fields
print(f"  Response keys: {[k for k in data.keys() if k != 'data']}")
if data.get("data"):
    last_id = data["data"][-1].get("id")
    print(f"  Last ID: {last_id}")
    # Try after param
    params2 = {"feedIds[]": [18588], "size": 5, "after": last_id}
    r2 = requests.get(url, headers=H, params=params2, timeout=10)
    data2 = r2.json()
    prods2 = data2.get("data", [])
    if prods2:
        print(f"  after={last_id}: {prods2[0].get('id')} | {prods2[0].get('title','')[:40]}")
        if prods2[0].get("id") != data["data"][0].get("id"):
            print("  ✅ Cursor pagination works!")
        else:
            print("  ❌ Same data returned")
