import requests
import gzip
import csv
import io

awin_token = 'bebd7839-013a-434d-a3da-7db2ecefb6b1'
publisher_id = 374301

# Try Awin product feed download for specific advertisers
# JD Sports: 8193, Foot Locker: 16092, adidas: 77016
advertisers = [8193, 16092, 77016, 8472]
names = {8193: 'JD Sports', 16092: 'Foot Locker', 77016: 'adidas', 8472: 'Schuurman'}

for adv_id in advertisers:
    # Awin product feed download URL format
    url = f'https://productdata.awin.com/datafeed/download/apikey/{awin_token}/language/nl/fid/{adv_id}/columns/aw_deep_link,product_name,aw_product_id,merchant_image_url,search_price,brand_name,colour,ean,model_number,in_stock,currency,rrp_price,merchant_category/format/csv/delimiter/%2C/compression/gzip/'
    print(f'\n{names.get(adv_id, adv_id)}: ', end='')
    try:
        r = requests.get(url, timeout=30, stream=True)
        print(f'{r.status_code} ({r.headers.get("Content-Type","")})')
        if r.ok:
            # Try to decompress and read first few lines
            content = r.content[:50000]  # First 50KB
            try:
                decompressed = gzip.decompress(content)
                lines = decompressed.decode('utf-8', errors='replace').split('\n')[:5]
                for line in lines:
                    print(f'  {line[:150]}')
                print(f'  ... ({len(decompressed)} bytes decompressed so far)')
            except:
                text = content.decode('utf-8', errors='replace')[:500]
                print(f'  Raw: {text}')
        else:
            print(f'  {r.text[:200]}')
    except Exception as e:
        print(f'  ERROR: {e}')
