import requests
import datetime
import sys

# Paste your credentials here
apikey    = "YOUR_API_KEY"
apisecret = "YOUR_API_SECRET"

apiurl = "https://api.codepunch.com/dnfeed/v2/"


def get_api_token():
    url      = f"{apiurl}auth/{apikey}/{apisecret}"
    response = requests.get(url)
    if response.status_code != 200:
        raise Exception(f"Authentication failed: {response.status_code}")
    data = response.json()
    if not data.get('status', False):
        raise Exception(data.get('error', 'Unknown error'))
    return data['token']


def download_zip(token, source, filename):
    url      = f"{apiurl}{token}/dailyzip/"
    params   = {"source": source}
    response = requests.get(url, params=params, stream=True)
    if response.status_code != 200:
        raise Exception(f"Download failed: {response.status_code}")
    total = 0
    with open(filename, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)
                total += len(chunk)
    print(f"Saved {filename}  ({total // 1024:,} KB)")


if __name__ == "__main__":
    # Usage:
    #   python dnfeed-daily-zip.py            # download added domains (default)
    #   python dnfeed-daily-zip.py added      # same as above
    #   python dnfeed-daily-zip.py deleted    # download deleted domains

    source = "added"
    if len(sys.argv) > 1:
        arg = sys.argv[1].strip().lower()
        if arg in ("added", "deleted"):
            source = arg
        else:
            print(f"Unknown option '{arg}'. Use 'added' or 'deleted'.")
            sys.exit(1)

    today    = datetime.date.today().strftime("%Y%m%d")
    filename = f"{source}_{today}.zip"

    print(f"Downloading {source} domains...")
    token = get_api_token()
    download_zip(token, source, filename)