#!/usr/bin/env python3
"""
CrossConnects - Networking Fundamentals, Episode 3: number conversion drills

Practice the conversions from the episode with random numbers:
  1. Binary to decimal         (8-bit binary  -> 0-255)
  2. Decimal to binary         (0-255         -> 8-bit binary)
  3. Hex to decimal            (two hex digits -> 0-255)
  4. Decimal to hex            (0-255         -> two hex digits)
  5. Hex to binary             (two hex digits -> 8-bit binary)
  6. Binary to hex             (8-bit binary  -> two hex digits)
  7. Mixed                     (a random pick of all of the above)

How to run it:
  Windows:      py crossconnects_number_drills.py
  Mac / Linux:  python3 crossconnects_number_drills.py

It only needs Python 3 (3.6 or newer). Nothing else to install.

Tips:
  - Binary answers can have spaces (1010 1100) or a 0b in front (0b10101100).
    Leading zeros are optional, so 101 and 00000101 are both fine.
  - Hex answers can be upper or lower case, with or without 0x in front.
  - Type q to quit at any time. You'll see your score at the end.
  - Get one wrong and you'll see the steps, worked the same way as in the episode.
"""

import random

PLACES = [128, 64, 32, 16, 8, 4, 2, 1]
HEX_DIGITS = "0123456789ABCDEF"


# ---------------------------------------------------------------- formatting
def to_bin(n):
    """0-255 as 8 bits, split into two nibbles: 172 -> '1010 1100'."""
    b = format(n, "08b")
    return b[:4] + " " + b[4:]


def to_hex(n):
    """0-255 as two hex digits: 172 -> 'AC'."""
    return format(n, "02X")


# ---------------------------------------------------------------- reading answers
def read_binary(text):
    t = text.strip().lower().replace(" ", "").replace("_", "")
    if t.startswith("0b"):
        t = t[2:]
    if not t or len(t) > 8 or any(c not in "01" for c in t):
        return None
    return int(t, 2)


def read_decimal(text):
    t = text.strip()
    if not t.isdigit():
        return None
    n = int(t)
    return n if 0 <= n <= 255 else None


def read_hex(text):
    t = text.strip().upper().replace(" ", "")
    if t.startswith("0X"):
        t = t[2:]
    if t.endswith("H"):
        t = t[:-1]
    if not t or len(t) > 2 or any(c not in HEX_DIGITS for c in t):
        return None
    return int(t, 16)


# ---------------------------------------------------------------- worked steps
def steps_bin_to_dec(n):
    bits = format(n, "08b")
    lines = ["Place values:  " + "  ".join(f"{p:>3}" for p in PLACES),
             "Bits:          " + "  ".join(f"{b:>3}" for b in bits)]
    on = [p for p, b in zip(PLACES, bits) if b == "1"]
    if on:
        lines.append("Add the places that have a 1: " + " + ".join(str(p) for p in on) + f" = {n}")
    else:
        lines.append("No bits are on, so the value is 0.")
    return lines


def steps_dec_to_bin(n):
    lines, left, bits = [], n, ""
    for p in PLACES:
        if p <= left:
            lines.append(f"Does {p:>3} fit into {left:>3}? Yes. Write 1, {left} - {p} leaves {left - p}.")
            left -= p
            bits += "1"
        else:
            lines.append(f"Does {p:>3} fit into {left:>3}? No.  Write 0.")
            bits += "0"
    lines.append(f"Reading down the column: {bits[:4]} {bits[4:]}")
    return lines


def nibble_line(d):
    v = int(d, 16)
    parts = [str(p) for p in (8, 4, 2, 1) if v & p]
    how = " + ".join(parts) if parts else "nothing"
    return f"{d} = {v:>2} = {format(v, '04b')}   ({how})"


def steps_hex_to_dec(n):
    h = to_hex(n)
    hi, lo = int(h[0], 16), int(h[1], 16)
    return [f"Left digit {h[0]} is {hi}, right digit {h[1]} is {lo}.",
            f"Multiply the left digit by 16 and add the right one: {hi} x 16 + {lo} = {hi * 16} + {lo} = {n}"]


def steps_dec_to_hex(n):
    hi, lo = divmod(n, 16)
    return [f"How many 16s fit into {n}? {hi}, because {hi} x 16 = {hi * 16}. That's the left digit: {HEX_DIGITS[hi]}.",
            f"What's left over? {n} - {hi * 16} = {lo}. That's the right digit: {HEX_DIGITS[lo]}.",
            f"So {n} is {to_hex(n)} (0x{to_hex(n)}).",
            "Another way: convert to binary, then read each nibble as one hex digit."]


def steps_hex_to_bin(n):
    h = to_hex(n)
    return ["One hex digit is exactly one nibble (4 bits). Convert each digit on its own:",
            "  " + nibble_line(h[0]), "  " + nibble_line(h[1]),
            f"Stick them together: {to_bin(n)}"]


def steps_bin_to_hex(n):
    b = format(n, "08b")
    return [f"Split the byte down the middle: {b[:4]} | {b[4:]}",
            "  " + nibble_line(to_hex(n)[0]), "  " + nibble_line(to_hex(n)[1]),
            f"So {to_bin(n)} is {to_hex(n)} (0x{to_hex(n)})."]


# ---------------------------------------------------------------- the drills
# name, prompt shown, how to read the answer, how to show the right answer, steps
DRILLS = {
    "1": ("Binary to decimal", lambda n: f"What is {to_bin(n)} in decimal?", read_decimal, str, steps_bin_to_dec),
    "2": ("Decimal to binary", lambda n: f"What is {n} in binary (8 bits)?", read_binary, to_bin, steps_dec_to_bin),
    "3": ("Hex to decimal", lambda n: f"What is 0x{to_hex(n)} in decimal?", read_decimal, str, steps_hex_to_dec),
    "4": ("Decimal to hex", lambda n: f"What is {n} in hex?", read_hex, to_hex, steps_dec_to_hex),
    "5": ("Hex to binary", lambda n: f"What is 0x{to_hex(n)} in binary (8 bits)?", read_binary, to_bin, steps_hex_to_bin),
    "6": ("Binary to hex", lambda n: f"What is {to_bin(n)} in hex?", read_hex, to_hex, steps_bin_to_hex),
}
WHAT_TO_TYPE = {read_decimal: "a decimal number from 0 to 255",
                read_binary: "up to 8 binary digits (0s and 1s)",
                read_hex: "one or two hex digits (0-9, A-F)"}


def ask(drill_key, n):
    """Ask one question. Returns True (right), False (wrong) or None (quit)."""
    name, prompt, reader, show, steps = DRILLS[drill_key]
    print(f"\n[{name}] {prompt(n)}")
    while True:
        text = input("> ").strip()
        if text.lower() in ("q", "quit", "exit"):
            return None
        answer = reader(text)
        if answer is None:
            print(f"  Type {WHAT_TO_TYPE[reader]}, or q to quit.")
            continue
        break
    if answer == n:
        print(f"  Correct! {show(n)}")
        return True
    print(f"  Not quite. You typed {show(answer)}, and the answer is {show(n)}. Here's how:")
    for line in steps(n):
        print("    " + line)
    return False


def menu():
    print("\nWhich drill?")
    for k, (name, *_ ) in DRILLS.items():
        print(f"  {k}. {name}")
    print("  7. Mixed")
    print("  q. Quit")
    while True:
        choice = input("> ").strip().lower()
        if choice in DRILLS or choice in ("7", "q", "quit", "exit"):
            return choice
        print("  Pick a number from 1 to 7, or q.")


def main():
    print("CrossConnects - Networking Fundamentals, Episode 3")
    print("Number conversion drills: binary, decimal, and hex (one byte, 0 to 255)")
    right = total = 0
    while True:
        choice = menu()
        if choice in ("q", "quit", "exit"):
            break
        print("Type q at any answer to go back to the menu.")
        while True:
            key = random.choice(list(DRILLS)) if choice == "7" else choice
            result = ask(key, random.randint(0, 255))
            if result is None:
                break
            total += 1
            right += result
            print(f"  Score: {right} of {total}")
    if total:
        print(f"\nFinal score: {right} of {total} ({round(100 * right / total)}%).")
    print("Thanks for practicing. See you in Episode 4!")


if __name__ == "__main__":
    try:
        main()
    except (KeyboardInterrupt, EOFError):
        print("\nBye!")
