#!/usr/bin/env python3
"""Discover TradeTracker feeds via SOAP with proper affiliate site handling."""
import requests
import re

SOAP_URL = 'https://ws.tradetracker.com/soap/affiliate'
HEADERS = {'Content-Type': 'text/xml; charset=utf-8'}

# Auth
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(SOAP_URL, data=soap_auth, headers={**HEADERS, 'SOAPAction': 'authenticate'}, timeout=15)
cookies = r.cookies
print(f'Auth: {r.status_code}')

# Get affiliate site IDs - the WSDL shows getAffiliateSitesByFilter might work
# Let's try getAffiliateSites with affiliateSiteFilter
soap_sites = '''<?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:getAffiliateSites>
      <ns:affiliateSiteFilter/>
    </ns:getAffiliateSites>
  </soap:Body>
</soap:Envelope>'''

r2 = requests.post(SOAP_URL, data=soap_sites, headers={**HEADERS, 'SOAPAction': 'getAffiliateSites'}, cookies=cookies, timeout=30)
print(f'\ngetAffiliateSites (with filter): {r2.status_code}')
print(f'Response: {r2.text[:2000]}')

# Extract site IDs
sites = re.findall(r'<item[^>]*>(.*?)</item>', r2.text, re.DOTALL)
print(f'Found {len(sites)} sites')
for s in sites:
    sid = re.search(r'<ID[^>]*>(.*?)</ID>', s)
    sname = re.search(r'<name[^>]*>(.*?)</name>', s)
    if sid:
        print(f'  Site: [{sid.group(1)}] {sname.group(1) if sname else "?"}')

# If we found a site, try getCampaigns with it
if sites:
    site_id = re.search(r'<ID[^>]*>(.*?)</ID>', sites[0]).group(1)
    print(f'\nUsing site ID: {site_id}')
    
    soap_campaigns = f'''<?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:getCampaigns>
      <ns:affiliateSiteID>{site_id}</ns:affiliateSiteID>
      <ns:campaignFilter/>
    </ns:getCampaigns>
  </soap:Body>
</soap:Envelope>'''

    r3 = requests.post(SOAP_URL, data=soap_campaigns, headers={**HEADERS, 'SOAPAction': 'getCampaigns'}, cookies=cookies, timeout=30)
    print(f'getCampaigns: {r3.status_code}')
    
    campaigns = re.findall(r'<item[^>]*>(.*?)</item>', r3.text, re.DOTALL)
    print(f'Found {len(campaigns)} campaigns')
    for c in campaigns[:50]:
        cid = re.search(r'<ID[^>]*>(.*?)</ID>', c)
        name = re.search(r'<name[^>]*>(.*?)</name>', c)
        if cid and name:
            cname = name.group(1)
            keywords = ['sneaker', 'schoen', 'shoe', 'sport', 'nike', 'adidas', 'puma', 'asics', 'foot', 'keep', 'mooie']
            is_relevant = any(kw in cname.lower() for kw in keywords)
            marker = ' ***' if is_relevant else ''
            print(f'  [{cid.group(1)}] {cname}{marker}')

    # Try getProductFeeds with site ID
    soap_pf = f'''<?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>
      <ns:affiliateSiteID>{site_id}</ns:affiliateSiteID>
    </ns:getProductFeeds>
  </soap:Body>
</soap:Envelope>'''

    r4 = requests.post(SOAP_URL, data=soap_pf, headers={**HEADERS, 'SOAPAction': 'getProductFeeds'}, cookies=cookies, timeout=30)
    print(f'\ngetProductFeeds: {r4.status_code}')
    feeds = re.findall(r'<item[^>]*>(.*?)</item>', r4.text, re.DOTALL)
    print(f'Found {len(feeds)} 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', 'mooie']
            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 url_match:
                print(f'    URL: {url_str[:200]}')
