#!/usr/bin/env python3
#
# pip_search - a workaround until pip_search is fixed
# dependencies: python3-prettytable
#
# see: https://github.com/victorgarric/pip_search/issues/44#issuecomment-2565442916

import hashlib
import re
import string
import sys

import bs4
import requests

# from prettytable import PrettyTable
from tabulate import tabulate

args = sys.argv

url = f"https://pypi.org/search/?q={args[1]}"
# 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]
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")])
mods = [i.text for i in soup.select(".package-snippet__name")]
mods_desc = [i.text for i in soup.select(".package-snippet__description")]

# table = PrettyTable()
# table.align = "l"
# table.field_names = ["Module", "Description"]
headers = ["Module", "Description"]
data = []

i = 0
for m in mods:
    # table.add_row([m, mods_desc[i]])
    data.add_row([m, mods_desc[i]])
    i += 1

# print(table)
print(tabulate(data, headers=headers, tablefmt="pretty"))
