import requests
import gzip

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

# Try Awin direct feed downloads
advertisers = {
    8193: 'JD Sports NL',
    16092: 'Foot Locker NL',
    77016: 'adidas NL',
    13498: 'ASICS NL',
}

print("=== AWIN FEEDS ===")
for adv_id, name in advertisers.items():
    url = f'https://productdata.awin.com/datafeed/download/apikey/{awin_token}/language/nl/fid/{adv_id}/columns/aw_deep_link,product_name,brand_name,search_price,ean,merchant_category/format/csv/delimiter/%2C/compression/gzip/'
    try:
        r = requests.get(url, timeout=20, stream=True)
        ct = r.headers.get('Content-Type', '')
        print(f'{name} ({adv_id}): HTTP {r.status_code} [{ct}]')
        if r.ok:
            chunk = r.raw.read(20000)
            try:
                data = gzip.decompress(chunk)
                lines = data.decode('utf-8', errors='replace').split('\n')[:4]
                for l in lines:
                    print(f'  {l[:150]}')
            except Exception:
                text = chunk.decode('utf-8', errors='replace')[:300]
                print(f'  Raw: {text}')
        else:
            print(f'  Error: {r.text[:200]}')
    except Exception as e:
        print(f'{name}: ERROR {e}')
    print()

# TradeTracker product feed
print("=== TRADETRACKER FEEDS ===")
tt_urls = [
    'https://pf.tradetracker.net/?aid=35058&encoding=utf-8&type=json&limit=5&q=sneakers',
    'https://pf.tradetracker.net/?aid=35058&encoding=utf-8&type=xml&limit=5&q=sneakers',
]
for url in tt_urls:
    try:
        r = requests.get(url, timeout=15)
        print(f'HTTP {r.status_code}: {url[:80]}')
        print(f'  {r.text[:500]}')
    except Exception as e:
        print(f'Error: {e}')
    print()

# Try TradeTracker SOAP to get feed list
print("=== TRADETRACKER SOAP ===")
soap_body = '''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:ns="http://schemas.tradetracker.com/affiliate">
  <soap:Body>
    <ns:authenticate>
      <ns:customerID>35058</ns:customerID>
      <ns:passphrase>bf0b9eef0da6caf55fe614518375280fe5c4ecca</ns:passphrase>
      <ns:sandbox>false</ns:sandbox>
      <ns:locale>nl_NL</ns:locale>
      <ns:demo>false</ns:demo>
    </ns:authenticate>
  </soap:Body>
</soap:Envelope>'''
try:
    r = requests.post('https://ws.tradetracker.com/soap/affiliate',
                      data=soap_body,
                      headers={'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'authenticate'},
                      timeout=15)
    print(f'Auth: {r.status_code}')
    # Extract session from response
    import re
    session_match = re.search(r'<session[^>]*>(.*?)</session>', r.text, re.DOTALL)
    if not session_match:
        session_match = re.search(r'<return[^>]*>(.*?)</return>', r.text, re.DOTALL)
    if session_match:
        print(f'Session/Return: {session_match.group(1)[:100]}')
    
    # Get cookies
    cookies = r.cookies
    print(f'Cookies: {dict(cookies)}')
    
    # Now get product feeds list using the session
    soap2 = '''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:ns="http://schemas.tradetracker.com/affiliate">
  <soap:Body>
    <ns:getFeeds>
      <ns:feedFilter>
        <ns:feedType>product</ns:feedType>
      </ns:feedFilter>
    </ns:getFeeds>
  </soap:Body>
</soap:Envelope>'''
    r2 = requests.post('https://ws.tradetracker.com/soap/affiliate',
                       data=soap2,
                       headers={'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'getFeeds'},
                       cookies=cookies,
                       timeout=30)
    print(f'getFeeds: {r2.status_code}')
    # Parse feed names
    feed_names = re.findall(r'<name[^>]*>(.*?)</name>', r2.text)
    feed_ids = re.findall(r'<ID[^>]*>(.*?)</ID>', r2.text)
    campaign_names = re.findall(r'<campaignName[^>]*>(.*?)</campaignName>', r2.text)
    print(f'Found {len(feed_names)} feeds')
    for i in range(min(30, len(feed_names))):
        fid = feed_ids[i] if i < len(feed_ids) else '?'
        cn = campaign_names[i] if i < len(campaign_names) else '?'
        print(f'  [{fid}] {feed_names[i]} - {cn}')

except Exception as e:
    print(f'SOAP Error: {e}')
    import traceback
    traceback.print_exc()
