#!/usr/bin/env python3
"""Discover TradeTracker product feeds."""
import requests
import re

soap_auth = '''<?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>'''

r = requests.post('https://ws.tradetracker.com/soap/affiliate', data=soap_auth,
    headers={'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'authenticate'}, timeout=15)
cookies = r.cookies
print(f'Auth: {r.status_code}')

soap_pf = '''<?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:getProductFeeds/>
  </soap:Body>
</soap:Envelope>'''

r3 = requests.post('https://ws.tradetracker.com/soap/affiliate', data=soap_pf,
    headers={'Content-Type': 'text/xml; charset=utf-8', 'SOAPAction': 'getProductFeeds'},
    cookies=cookies, timeout=30)
print(f'getProductFeeds: {r3.status_code}')
feeds = re.findall(r'<item[^>]*>(.*?)</item>', r3.text, re.DOTALL)
print(f'Found {len(feeds)} product feeds')
for f in feeds:
    fid = re.search(r'<ID[^>]*>(.*?)</ID>', f)
    name = re.search(r'<name[^>]*>(.*?)</name>', f)
    pcount = re.search(r'<productCount[^>]*>(.*?)</productCount>', f)
    camp_name = re.search(r'<campaignName[^>]*>(.*?)</campaignName>', f)
    url_match = re.search(r'<URL[^>]*>(.*?)</URL>', f)
    if fid and name:
        n = name.group(1)
        cn = camp_name.group(1) if camp_name else '?'
        pc = pcount.group(1) if pcount else '?'
        url_str = url_match.group(1) if url_match else ''
        keywords = ['sneaker', 'schoen', 'shoe', 'sport', 'nike', 'adidas', 'puma', 'asics', 'foot', 'keep']
        is_relevant = any(kw in n.lower() or kw in cn.lower() for kw in keywords)
        marker = ' ***' if is_relevant else ''
        print(f'[{fid.group(1)}] {n} ({cn}) [{pc} products]{marker}')
        if is_relevant:
            print(f'  URL: {url_str[:200]}')
