#!/usr/bin/env python3
"""Try Awin product feeds via direct download URLs."""
import requests
import gzip
import io

TOKEN = 'bebd7839-013a-434d-a3da-7db2ecefb6b1'
PUB_ID = '374301'

# Awin datafeed download URLs - try different formats
# Format: https://productdata.awin.com/datafeed/download/apikey/{token}/language/nl/fid/{feedId}/...
# We need to find the feed IDs first

# Try getting merchant feed lists via the newer API endpoint
print("=== Try Awin Merchant Feeds API ===")
headers = {'Authorization': f'Bearer {TOKEN}'}

# Try the publishers API to get advertiser details with feed info
advertisers = {
    8193: 'JD Sports NL',
    16092: 'Foot Locker NL', 
    77016: 'adidas NL',
    8472: 'Schuurman Schoenen',
}

for adv_id, name in advertisers.items():
    print(f"\n--- {name} ({adv_id}) ---")
    
    # Try getting programme details which may include feed info
    r = requests.get(f'https://api.awin.com/publishers/{PUB_ID}/programmes/{adv_id}',
                     headers=headers, timeout=15)
    if r.status_code == 200:
        data = r.json()
        print(f"  Programme: {data.get('name')}")
        print(f"  Has feeds: {data.get('hasProductFeed', '?')}")
        print(f"  Primary sector: {data.get('primarySector', {}).get('name', '?')}")
    else:
        print(f"  Programme API: {r.status_code}")

    # Try direct datafeed download with advertiser ID as feed ID
    # Awin uses advertiserId as the feed identifier
    urls_to_try = [
        f'https://productdata.awin.com/datafeed/download/apikey/{TOKEN}/language/nl/fid/{adv_id}/columns/aw_deep_link,product_name,aw_product_id,merchant_product_id,merchant_image_url,description,merchant_category,search_price,merchant_name,brand_name,aw_image_url,currency,store_price,delivery_cost,merchant_deep_link,colour,data_feed_id,ean/format/csv/delimiter/%2C/compression/gzip/',
        f'https://productdata.awin.com/datafeed/download/apikey/{TOKEN}/language/nl/cid/{adv_id}/columns/aw_deep_link,product_name,search_price,brand_name,merchant_category/format/csv/delimiter/%2C/compression/gzip/showExtraFields/1/',
    ]
    
    for i, url in enumerate(urls_to_try):
        r2 = requests.get(url, timeout=30, stream=True)
        print(f"  Download attempt {i+1}: {r2.status_code} ({r2.headers.get('content-type', '?')[:50]})")
        if r2.status_code == 200:
            content = r2.content
            print(f"    Size: {len(content)} bytes")
            if content[:2] == b'\x1f\x8b':
                try:
                    text = gzip.decompress(content).decode('utf-8', errors='replace')
                    lines = text.split('\n')
                    print(f"    Lines: {len(lines)}")
                    for line in lines[:3]:
                        print(f"    {line[:200]}")
                except Exception as e:
                    print(f"    Decompress error: {e}")
            else:
                print(f"    Content: {content[:500].decode('utf-8', errors='replace')}")
            break
        elif r2.status_code != 500:
            print(f"    Response: {r2.text[:200]}")
