#!/usr/bin/env python
import sys

from requests import get
from requests.exceptions import HTTPError, RequestException

TIMEOUT = 30
MAX_TRIES = 2

tries = 0


def archive_web_page(url):
    global tries
    # Format the URL for the API call
    tries += 1
    api_url = f"http://web.archive.org/save/{url}"
    try:
        # Send the API request
        response = get(api_url, timeout=TIMEOUT)
        response.raise_for_status()  # Raise an exception for any error status codes

        if response.status_code == 200:
            print("Web page archived successfully!")

    except (RequestException, HTTPError) as e:
        if tries < MAX_TRIES:
            print(
                f"An error occurred: {e}\n"
                f"Trying again. Try: {tries+1}/{MAX_TRIES}"
            )
            archive_web_page(url)
        raise RequestException(f"Couldn't archive {url}")


if len(sys.argv) < 2:
    print("Usage: python archive.py <url>")
    sys.exit(1)

# Archive the web page
archive_web_page(sys.argv[1])
