# ======================================================================================================================
 
# Authors: BERKYT, Walgala, Александр Хаметзянов
 
# ======================================================================================================================
 
# Формат флага: XXX{}
# Формат ссылки: https://task1.tasks.rubikoid.ru/md5(c3e97dd6e97fb5125688c97f36720cbe + secret + .php
 
import hashlib
import random
import re
import threading

from rich.console import Console
from selenium import webdriver
from selenium.webdriver.common.by import By
 
 
link = 'https://task1.tasks.rubikoid.ru/c3e97dd6e97fb5125688c97f36720cbe.php'
path_to_browser = r"D:\Downloads\chromedriver.exe"
console = Console()
ignore_words = ['Approved! Use secret to create a link for next step! next Chain step secret is:', 'Lorem', 
'gimmie a value whose MD5 ends with this 4 chars from captcha: ', 'Cmon Human!']


def log(data: str):
    with open('tmp_log.txt', 'a') as log_file:
        log_file.write(str(data) + '\n')


def generate_key(alphabet: str = '0123456789abcdefghijklmnopqrstuvwxyz', length: int = 4) -> str:
    key = ''
 
    for _ in range(length):
        key += random.choice(alphabet)
 
    return key
 
 
def parse_html( responce: str, pattern: str = r'(?<=name="hash" value=").+?(?=")') -> list:
    return re.findall(pattern, responce)
 
 
def get_secret(sourse_code_site: list) -> str:
    for line in sourse_code_site:
        secret = parse_html(line, r'(?<=<br>).+?(?=<br>)')

        if secret:
            console.print(f'Вариант секрета: {secret[0]=}')
            if secret[0] not in ignore_words:
                return secret[0]

            console.print(f'Неверно!', style='bold underline red')


def get_hash(sourse_code_site: list) -> str:
    for line in sourse_code_site:
        hash_capture = parse_html(line)
 
        if hash_capture:
            return hash_capture[0]
    else:
        raise Exception('На сайте нет хеша.')
 
 
def decrypt_md5(target_hash: str) -> str:
    with console.status('[bold green]Waiting...[/bold green]'):
        while True:
            decrypt_hash = generate_key()
            hash_object = hashlib.md5(decrypt_hash.encode('utf-8'))
 
            if hash_object.hexdigest() == target_hash:
                return decrypt_hash
 

# создает хеш с 4 символами который совпадает с 4 последними символами капчи 
def find_target_hash(sub_line: str) -> tuple[str, str]:
    with console.status('[bold green]Waiting...[/bold green]'):
        while True:
            target_decrypt_hash = generate_key()
            hash_object = hashlib.md5(target_decrypt_hash.encode('utf-8'))
            hash_str = str(hash_object.hexdigest())
 
            if hash_str[-4:] == sub_line:
                return hash_str, target_decrypt_hash
 
 
def get_sourse_code_site() -> list:
    global driver
    return str(driver.page_source).split(r'\n')
 

def find_secret():
    while True:
        global driver
        #  гавно с открытием 
        options = webdriver.ChromeOptions() 
        driver = webdriver.Chrome(options=options, executable_path=path_to_browser)
        driver.get(link)

        sourse_code_site = get_sourse_code_site()
        hash_capture = get_hash(sourse_code_site)
        decrypt_hash_capture = decrypt_md5(hash_capture)
        new_hash, key = find_target_hash(decrypt_hash_capture)
        
        print(f'{hash_capture=}; {decrypt_hash_capture=}')
        print(f'{new_hash=}; {key=}')
        
        driver.find_element(By.NAME, "ch").send_keys(key)
        driver.find_element(By.NAME, "s").click()

        refreshed_sourse_code_site = get_sourse_code_site()
        secret = get_secret(refreshed_sourse_code_site)
        console.print(f'{secret=}', style='bold underline red')

        log([secret, new_hash, key, decrypt_hash_capture, hash_capture])

        if secret not in ignore_words and secret is not None:
            break
            
    console.print('Секрет найден!', style='bold underline red')
    print(get_sourse_code_site())
    console.print(f'{secret=}', style='bold underline red')
    log([secret, new_hash, key, decrypt_hash_capture, hash_capture, 'ЭТОТ ЛОГ С СЕКРЕТОМ!'])


# for _ in range(10):
#     thread = threading.Thread(
#         target=find_secret
#     )
#     thread.start()

find_secret()
input('Нажмите любую кнопку, чтобы закрыть...')
