#!/usr/bin/env python3
"""Solve a Forbidden Peach proof-of-work challenge.

Usage:  python3 pow-solver.py HASH HEX_CHARS

HASH is the 40 character SHA-1 hex digest from the challenge. HEX_CHARS is the length of
the hidden secret. The secret is HEX_CHARS lowercase hex characters (0-9, a-f) whose
SHA-1 digest is HASH. This tries every candidate and prints the one that matches.
HEX_CHARS is 5 or 6, so it finishes in a few seconds.
"""

import hashlib
import sys


def solve(target: str, length: int) -> str | None:
    width = f"0{length}x"
    sha1 = hashlib.sha1
    for number in range(16**length):
        guess = format(number, width)
        if sha1(guess.encode()).hexdigest() == target:
            return guess
    return None


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: pow-solver.py HASH HEX_CHARS")
    answer = solve(sys.argv[1].strip().lower(), int(sys.argv[2]))
    if answer is None:
        sys.exit("no solution: check the hash and the length")
    print(answer)
