#!/usr/bin/env python3
"""Try filtering by brand to get more products"""
import requests, json

API = "https://platform-api.webgains.com"
PUB = "1347930"
TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxMDAwMzEiLCJqdGkiOiIwNjM5ODEwYzQ0YzM1MTBlZmZiMGRkYWNiM2EyNWFlNTg2YzFmNmQ5ODNjNGQ2MDA4NzkwZmM0NTkzY2EyNjg4ZGViZDE4NTgwOThmYjJjYiIsImlhdCI6MTc3MTUxNjc4OS44MzAxMzUsIm5iZiI6MTc3MTUxNjc4OS44MzAxMzcsImV4cCI6MjA4NzA0OTU4OS44MjcwODgsInN1YiI6IjIwMTcwOCIsInNjb3BlcyI6W119.ZxlCDsyBI7_SNUWjO-PUxDYKvQVfuUBzU5n-SgqHdAZCnOj9253yVcJIS5NRXJLrnyx0E_9bn8ymfXS71cvPISA4hPAlKCSMjdkv9f2k2FFwdAlQQ6mdhBB2m9dzHUIn34QwA8s4-ikB1ATKIZeqiJL-3Gh9eiMYPpvaJdCCjN-oGPMhhlehkgA04cZSgwy6HfKgb6uPvUSG9w_tvN8U06uEHKV11DedQHNWWGzuXpd2FEL3baV0z9KjSNMZsJZHx2yHUb6gVWJwaR7_louahMvrPXG-YLgnGvNMcPDPjm-z5HJ-JKcPv9_FBqAYGItZxgeGgVoS8MVhW6lc1a-6CvYtVanfXF42MPPNP-Qq76qRtHPLRBdkIATMuBxVJrMzlprT3n4F0sUUltGR4ixZuzMUm5LeyPMHgmjy2UfYzsl9eVqx0oJCmKUyY9maBXwFLJa8J1NHM_nWp3hPpCGkMyhzHK1DIf_z8Wirg1hp5vKts93eERWJBlQwhucUUS_KnZeC_gVaQ7kT4jCwaEWkpPxPxyXWRoK0mcYS_JGz3JbpVhRLj5DVYIB9k54DXqjYlCx8ezJZE9sf2SX3VWvPvD1xSQD1caTCm0To0B-MkeU1YpEfWdUslpCJXrpOy2Wbs8iDHR1BzNrMnOEr4zbz_EoB4JJe3tGTGjzNLNIw6XI"
H = {"Authorization": f"Bearer {TOKEN}"}
CAMP = "1622230"

url = f"{API}/auth/publishers/{PUB}/campaigns/{CAMP}/feeds/products"

# First, get available brands/facets
print("=== Check response structure for facets ===")
r = requests.get(url, headers=H, params={
    "feeds[]": [17108],
    "size": 1,
    "fields[]": ["title", "id", "brand"],
}, timeout=30)
data = r.json()
# Print all top-level keys
print(f"Top-level keys: {list(data.keys())}")
for k, v in data.items():
    if k != "data":
        print(f"  {k}: {json.dumps(v, default=str)[:200]}")

# Try to get brand list via aggregation/facets
print("\n=== Try aggregation endpoint ===")
agg_urls = [
    f"{API}/auth/publishers/{PUB}/campaigns/{CAMP}/feeds/products/brands",
    f"{API}/auth/publishers/{PUB}/campaigns/{CAMP}/feeds/products/facets",
    f"{API}/auth/publishers/{PUB}/campaigns/{CAMP}/feeds/products/aggregations",
    f"{API}/auth/publishers/{PUB}/campaigns/{CAMP}/feeds/brands",
]
for aurl in agg_urls:
    r = requests.get(aurl, headers=H, timeout=10)
    print(f"  {aurl.split('/')[-1]}: {r.status_code}")
    if r.status_code == 200:
        print(f"    {r.text[:500]}")

# Try fetching with brand filter for specific feeds
print("\n=== Per-feed with brand filter ===")
sneaker_brands = ["Nike", "Adidas", "New Balance", "ASICS", "Puma", "Converse", "Reebok", "Vans", "Jordan"]
feed_id = 17108  # Van Arendonk - 21850 products

all_ids = set()
for brand in sneaker_brands:
    r = requests.get(url, headers=H, params={
        "feeds[]": [feed_id],
        "size": 1000,
        "fields[]": ["title", "id", "brand"],
        "filters[brand][]": brand,
    }, timeout=30)
    data = r.json()
    products = data.get("data", [])
    ids = set(p["id"] for p in products)
    new_ids = ids - all_ids
    all_ids |= ids
    total = data.get("recordsTotal", "?")
    print(f"  {brand}: {len(products)} products (total={total}), {len(new_ids)} new, cumulative: {len(all_ids)}")

# Also try search query
print("\n=== Search queries ===")
queries = ["sneaker", "schoen", "boot", "sandaal", "slipper"]
for q in queries:
    r = requests.get(url, headers=H, params={
        "feeds[]": [feed_id],
        "size": 1000,
        "fields[]": ["title", "id", "brand"],
        "q": q,
    }, timeout=30)
    data = r.json()
    products = data.get("data", [])
    ids = set(p["id"] for p in products)
    new_ids = ids - all_ids
    all_ids |= ids
    print(f"  q='{q}': {len(products)} products, {len(new_ids)} new, cumulative: {len(all_ids)}")
