import time

import requests
import bs4
from prometheus_client import start_http_server, Gauge

IN_STOCK = Gauge("valve_index_in_stock", "Valve index in stock?")


def fetch_in_stock():
    resp = requests.get("https://store.steampowered.com/valveindex")
    resp.raise_for_status()

    soup = bs4.BeautifulSoup(resp.text, 'html.parser')
    form = soup.find('form', attrs=dict(name='add_to_cart_354231'))
    if not form:
        raise Exception("couldn't find add to cart form")
    price = form.parent.find('div', class_='game_purchase_price')
    if not price:
        raise Exception("couldn't find price")
    green_btn = price.parent.find('span', class_='btn_disabled')
    if green_btn:
        return 0
    return 1


def main(argv):
    if argv:
        raise Exception("too many arguments")

    IN_STOCK.set_function(fetch_in_stock)
    start_http_server(9998)
    while True:
        time.sleep(1000)


if __name__ == "__main__":
    import sys

    main(sys.argv[1:])