#!/usr/bin/env python3
"""Try Webgains classic feed download URLs and other approaches."""
import requests, json, csv, io

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"
PUBLISHER_ID = "1347930"
H = {"Authorization": f"Bearer {TOKEN}"}

# Try classic Webgains feed download URLs
# Format: https://feeds.webgains.com/download/{feed_id}.csv?key=...
# Or: https://productdata.webgains.com/...
classic_urls = [
    "https://feeds.webgains.com/download/18588.csv",
    "https://productdata.webgains.com/download/18588.csv",
    f"https://platform-api.webgains.com/auth/publishers/{PUBLISHER_ID}/feeds/18588",
    f"https://platform-api.webgains.com/auth/feeds/18588",
    f"https://platform-api.webgains.com/auth/publishers/{PUBLISHER_ID}/feeds/18588/export",
]

for url in classic_urls:
    try:
        r = requests.get(url, headers=H, timeout=10, allow_redirects=True)
        print(f"{r.status_code} {url}")
        if r.status_code == 200:
            print(f"  Content-Type: {r.headers.get('content-type')}")
            print(f"  Size: {len(r.content)} bytes")
            print(f"  First 200 chars: {r.text[:200]}")
    except Exception as e:
        print(f"ERR {url}: {e}")

# Try the Webgains product search API with specific feed
print("\n=== Try GraphQL or other API ===")
# Check if there's a GraphQL endpoint
for ep in ["/graphql", "/api/graphql", "/v2/feeds/18588/products"]:
    url = f"https://platform-api.webgains.com{ep}"
    try:
        r = requests.get(url, headers=H, timeout=5)
        print(f"{r.status_code} {ep}: {r.text[:100]}")
    except Exception as e:
        print(f"ERR {ep}: {e}")

# Try the feed with actual different query params
print("\n=== Try proper feed filtering ===")
url = f"https://platform-api.webgains.com/auth/publishers/{PUBLISHER_ID}/campaigns/1622230/feeds/products"
# The key insight: maybe we need to pass feedIds not feeds[]
for param_name in ["feedIds", "feed_ids", "feedId", "feed"]:
    params = {param_name: "18588", "size": 2, "fields[]": ["title", "brand"]}
    r = requests.get(url, headers=H, params=params, timeout=10)
    data = r.json()
    p = data.get("data", [{}])[0] if data.get("data") else {}
    total = data.get("recordsTotal", "?")
    print(f"  {param_name}=18588 -> total={total}, first={p.get('brand','')} {p.get('title','')[:40]}")

# Try POST instead of GET
print("\n=== Try POST ===")
r = requests.post(url, headers={**H, "Content-Type": "application/json"}, 
                  json={"feeds": [18588], "size": 2, "fields": ["title", "brand"]}, timeout=10)
print(f"POST {r.status_code}: {r.text[:200]}")
