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ID = "1347930"
H = {"Authorization": f"Bearer {TOKEN}", "Accept": "application/json"}

url = f"https://platform-api.webgains.com/auth/publishers/{PUBLISHER_ID}/campaigns/1622230/feeds/products"

# Test feedIds as array
print("=== feedIds[] format ===")
params = {"feedIds[]": [18588], "size": 5, "fields[]": ["title", "brand", "id"]}
r = requests.get(url, headers=H, params=params, timeout=10)
data = r.json()
print(f"recordsTotal: {data.get('recordsTotal')}")
print(f"recordsFiltered: {data.get('recordsFiltered')}")
for p in data.get("data", [])[:5]:
    print(f"  {p.get('id')} | {p.get('brand')} | {p.get('title','')[:60]}")

# Compare with feeds[] 
print("\n=== feeds[] format ===")
params2 = {"feeds[]": [18588], "size": 5, "fields[]": ["title", "brand", "id"]}
r2 = requests.get(url, headers=H, params=params2, timeout=10)
data2 = r2.json()
print(f"recordsTotal: {data2.get('recordsTotal')}")
print(f"recordsFiltered: {data2.get('recordsFiltered')}")
for p in data2.get("data", [])[:5]:
    print(f"  {p.get('id')} | {p.get('brand')} | {p.get('title','')[:60]}")

# Try with programs[] filter (program_id for Baskets = 299740)
print("\n=== programs[] filter ===")
params3 = {"programs[]": [299740], "size": 5, "fields[]": ["title", "brand", "id", "feed_id"]}
r3 = requests.get(url, headers=H, params=params3, timeout=10)
data3 = r3.json()
print(f"recordsTotal: {data3.get('recordsTotal')}")
for p in data3.get("data", [])[:5]:
    print(f"  {p.get('id')} | {p.get('brand')} | {p.get('title','')[:60]} | feed_id={p.get('feed_id')}")

# Also print ALL keys from first product to see what's available
print("\n=== All product fields (no field filter) ===")
params4 = {"feedIds[]": [18588], "size": 1}
r4 = requests.get(url, headers=H, params=params4, timeout=10)
data4 = r4.json()
if data4.get("data"):
    p = data4["data"][0]
    print(f"Keys: {sorted(p.keys())}")
    print(json.dumps(p, indent=2, default=str)[:1500])

# Try Webgains docs URL
print("\n=== Check API docs ===")
for doc_url in [
    "https://docs.webgains.dev/docs/platform-api-1",
    "https://docs.webgains.dev/reference",
    "https://api.webgains.com/2.0/product-feeds",
]:
    try:
        r = requests.get(doc_url, timeout=5)
        print(f"{r.status_code} {doc_url} ({len(r.content)} bytes)")
    except Exception as e:
        print(f"ERR {doc_url}: {e}")
