#!/usr/bin/env python3

import hashlib
import re
import string

import bs4
import requests

url = "https://pypi.org/search/?q=pip-search"

session = requests.Session()
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
}
resp = session.get(url, headers=headers)
print(resp.status_code)
print(resp.cookies)
# print(resp.text)

# Get script.js url
pattern = re.compile(r"/(.*)/script.js")
path = pattern.findall(resp.text)[0]
script_url = f"https://pypi.org/{path}/script.js"
print(script_url)

resp = session.get(script_url)
print(resp.status_code)
print(resp.text[-521:])

# Find the PoW data from script.js
# TODO: make the pattern more robust
pattern = re.compile(
    r'init\(\[\{"ty":"pow","data":\{"base":"(.+?)","hash":"(.+?)","hmac":"(.+?)","expires":"(.+?)"\}\}\], "(.+?)"'
)
base, hash, hmac, expires, token = pattern.findall(resp.text)[0]  # noqa: A001
print(base, hash, hmac, expires, token, sep="\n")

# Compute the PoW answer
answer = ""
characters = string.ascii_letters + string.digits
for c1 in characters:
    for c2 in characters:
        c = base + c1 + c2
        if hashlib.sha256(c.encode()).hexdigest() == hash:
            answer = c1 + c2
            break
    if answer:
        break
print(answer)

# Send the PoW answer
back_url = f"https://pypi.org/{path}/fst-post-back"
data = {
    "token": token,
    "data": [
        {"ty": "pow", "base": base, "answer": answer, "hmac": hmac, "expires": expires}
    ],
}
resp = session.post(back_url, json=data)
print(resp.status_code)
print(resp.text)

# TODO: save the cookies
print(session.cookies)

# Get the search result with new cookies
resp = session.get(url)
print(resp.status_code)

soup = bs4.BeautifulSoup(resp.text, "html.parser")
print([i.text for i in soup.select(".package-snippet__name")])
