# ============================================================
#  Lab checker and hand-in tool
#
#  HOW TO USE: open this file in Thonny and press Run (F5) once.
#  It runs every task file in this folder and shows you a report,
#  then asks what you want to do next. Edit a task, press 1 again:
#  check as often as you like -- it never changes your files.
#
#  One copy serves every lab and assignment this term: it asks the
#  grader what is open and tells by the files in this folder.
# ============================================================

ACTIVITY = ""
BASE_URL = "https://fakhirshaheen.com/handin/api"

# ------------------------------------------------------------
# Nothing below here needs editing.
# ------------------------------------------------------------

import base64
import datetime
import json
import os
import socket
import ssl
import subprocess
import sys
import re
import textwrap
import threading
import time
import urllib.error
import urllib.request
from fnmatch import fnmatchcase

FORMAT = 1
# Sent with every request. The server serves the version it hands out and
# turns every older one away with one sentence saying where the current
# file is, so an old copy in a student's folder cannot quietly keep working.
# Bumping it therefore retires every copy already out, the day the server
# is deployed: bump it for a change that has to reach those folders, and
# rebuild the site's kits in the same sitting, which carry a copy too.
# 4: asks a task's questions before it opens, and runs only open tasks.
# 5: Enter at a key checks the open tasks rather than ending the check. The
#    server needs nothing new; the number tells the copies apart on a row.
# 6: leaves out files whose names the server would refuse, comes back to the
#    menu after an error it did not expect, and asks what is open once a run
#    rather than before every action. The server needs nothing new. It also
#    reads where the chain stands off the receipt's reply (X-Grader-Chain)
#    when the server sends that, and asks /plan for it as before when not.
# 7: runs a task that has Shell lines under the harness the plan carries,
#    and sends what the Shell showed beside what the program printed. An
#    activity with such a task turns older copies away.
# 8: says which account and which computer it ran on, beside its version.
#    The server needs neither. A copy older than 8 is turned away as every
#    older copy is, for being older than the one handed out.
# 9: says the same with each answer to a key, so the instructors' board
#    knows where a student sits before their first check. The server needs
#    none of it.
# 10: has "skip" on its menu, which leaves the task the student is on for
#    now, and offers nothing of the kind after a report. The server lets a
#    task be skipped from the moment it opens (10 Oct 2026), so a copy
#    older than 10 would ask "m or Enter" after every failed check.
CLIENT_VERSION = 10
HERE = os.path.dirname(os.path.abspath(__file__))
# Where a student gets a code. The API lives one segment below the page, so
# this is BASE_URL without its trailing /api rather than a second thing to
# keep in step. Written without its https://, the way the grader's own
# messages write it, so one screen never spells the page two ways.
TOKEN_PAGE = ((BASE_URL[:-len("/api")] if BASE_URL.endswith("/api")
               else BASE_URL).split("://", 1)[-1]
              or "your instructor's grader page")
# The file names the grader stores: FILENAME_RE of grader/store.py, and a
# test holds the two equal. The server is what enforces it, and it refuses
# the whole request over one such name; this copy decides nothing, it only
# keeps a stray "task05 - Copy.py" from costing a student their check.
FILENAME_RE = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}\Z")
NETWORK_TIMEOUT = 60
STDERR_TAIL = 4096
WIDTH = 60      # nothing this file prints is wider than this
RULE = 54       # as wide as the bars of the grader's report

OK, CRASH, TIMEOUT, TOO_MUCH_OUTPUT, MISSING = (
    "OK", "CRASH", "TIMEOUT", "TOO_MUCH_OUTPUT", "MISSING")

# A task with Shell lines is run by the harness the plan carries, which
# writes a record after the program's own output: MARK opens each one, and
# SHELL_ROOM is how much the records may add to what the pipe is let hold.
MARK = "\x1e"
SHELL_ROOM = 128 * 1024

OFFLINE = ("Could not reach the grader. Your files are unchanged; try again "
           "in a minute.")

# The grader's certificate comes from Let's Encrypt, whose chain ends at
# one of these two roots. Normally the machine's own certificate store
# vouches for them; this copy is for when it cannot. Windows caches every
# intermediate certificate it meets, Python on Windows trusts that cache,
# and Let's Encrypt has re-issued intermediates under the same name: a
# 2020 copy of "ISRG Root X2" expired in September 2025, and a laptop that
# still holds it prefers it to the fresh one the grader sends, so every
# check fails with "certificate has expired" while the site opens fine
# in a browser. When the store's verdict is a certificate failure, the
# request is made once more trusting only these roots, which nothing on
# the machine can shadow. Both are public and expire in 2035 and 2040.
# Source: https://letsencrypt.org/certificates/
ISRG_ROOTS = """\
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IF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KoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW
+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9
ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T
AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI
zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW
tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
/q4AaOeMSQ+2b1tbFfLn
-----END CERTIFICATE-----
"""


# ------------------------------------------------------------
# Running one task file. Same rules as the server's own runner, so a
# result here means the same thing as a result there.
# ------------------------------------------------------------

def run_task(folder, filename, stdin_text, timeout_seconds, cap_bytes,
             shell=None, harness=None, watch=False):
    """Run one task file and record what happened. No opinion on whether
    it was right: only the server decides that.

    With `shell` (a list of lines, possibly empty) and `harness` (the
    plan's program for typing them), the file is run by that program, which
    then types the lines into the Shell the run left behind; the record
    gains "shell", what the Shell showed. `watch` asks it to count calls."""
    path = os.path.join(folder, filename)
    if not os.path.isfile(path):
        return {"file": filename, "status": MISSING, "exit_code": None,
                "signal": None, "stdout": "", "stderr_tail": "", "wall_ms": 0}

    env = dict(os.environ)
    env["PYTHONIOENCODING"] = "utf-8"
    command, limit, nonce = [sys.executable, filename], cap_bytes, None
    if shell is not None and harness:
        # Started as python -c, so the harness is never a file in this
        # folder. The nonce is this run's alone: it marks which of the
        # lines on stdout are the harness's and not the program's.
        nonce = base64.b16encode(os.urandom(8)).decode("ascii")
        env["GRADER_SHELL"] = json.dumps({"nonce": nonce, "lines": shell,
                                          "watch": bool(watch)})
        command = [sys.executable, "-c", harness, filename]
        limit = cap_bytes + SHELL_ROOM
    started = time.time()
    process = subprocess.Popen(
        command, cwd=folder, env=env,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    over = threading.Event()
    out_chunks, err_chunks = [], []
    threads = [
        threading.Thread(target=_feed, args=(process.stdin, stdin_text)),
        threading.Thread(target=_drain, args=(process.stdout, out_chunks,
                                              limit, over)),
        threading.Thread(target=_drain, args=(process.stderr, err_chunks,
                                              None, None)),
    ]
    for thread in threads:
        thread.daemon = True
        thread.start()

    deadline = started + timeout_seconds
    status = None
    while process.poll() is None:
        if over.is_set():
            status = TOO_MUCH_OUTPUT
            break
        if time.time() >= deadline:
            status = TIMEOUT
            break
        time.sleep(0.02)
    if status is not None:
        try:
            process.kill()
        except OSError:
            pass
    process.wait()
    wall_ms = int((time.time() - started) * 1000)
    for thread in threads:
        thread.join(timeout=1.0)
    for stream in (process.stdin, process.stdout, process.stderr):
        try:
            stream.close()
        except (OSError, ValueError):
            pass

    code = process.returncode
    if status is None:
        status = OK if code == 0 else CRASH
    printed = b"".join(out_chunks)
    record = {"file": filename,
              "status": status,
              "exit_code": code if code is not None and code >= 0 else None,
              "signal": -code if code is not None and code < 0 else None,
              "stdout": printed[:cap_bytes].decode("utf-8", "replace"),
              "stderr_tail": b"".join(err_chunks)[-STDERR_TAIL:].decode(
                  "utf-8", "replace"),
              "wall_ms": wall_ms}
    if nonce is not None:
        text, said = split_shell(printed[:limit].decode("utf-8", "replace"),
                                 nonce)
        own = text.encode("utf-8")
        # The cap is on what the program itself printed, as it is for a
        # task run plainly; the harness's records are not counted in it.
        if len(own) > cap_bytes:
            record["status"] = TOO_MUCH_OUTPUT
            text = own[:cap_bytes].decode("utf-8", "replace")
        record["stdout"] = text
        record["shell"] = said
    return record


def split_shell(text, nonce):
    """What a run under the harness wrote, parted in two: what the program
    itself printed, and the Shell's record (contract section 2.4a).

    The harness opens each of its records with MARK and this run's nonce,
    so the program's own output is everything before the first of them. A
    record that cannot be read is dropped: no opinion here either.
    """
    pieces = text.split(MARK + nonce + " ")
    program, lines = None, []
    for piece in pieces[1:]:
        try:
            fields = json.loads(piece.split("\n", 1)[0])
        except ValueError:
            continue
        if not isinstance(fields, dict):
            continue
        if fields.get("kind") == "program":
            program = {"status": fields.get("status"),
                       "calls": fields.get("calls")}
        elif fields.get("kind") == "line":
            fields.pop("kind")
            lines.append(fields)
    return pieces[0], {"program": program, "lines": lines}


def _feed(stream, text):
    try:
        stream.write(text.encode("utf-8"))
        stream.close()
    except (OSError, ValueError):
        pass


def _drain(stream, chunks, limit, over):
    total = 0
    try:
        while True:
            block = stream.read(4096)
            if not block:
                break
            chunks.append(block)
            total += len(block)
            if limit is not None and total > limit:
                over.set()
                break
    except (OSError, ValueError):
        pass


# ------------------------------------------------------------
# How everything is printed. One shape for the whole program, so a
# student can tell at a glance what is progress and what went wrong:
# a header line per action, two spaces in, a "!" in front of every
# problem, and nothing wider than WIDTH.
# ------------------------------------------------------------

# Colour is ANSI escape codes, which Thonny's shell and every terminal
# render, so nothing needs installing. It is switched off wherever the codes
# would show as text: IDLE, a file, a pipe, or when NO_COLOR is set. Nothing
# is said in colour alone; the words carry the meaning without it.
GREEN, RED, AMBER, CYAN, BOLD, DIM = "32", "31", "33", "36", "1", "2"


def _colour_works():
    if os.environ.get("NO_COLOR"):
        return False
    if "idlelib" in sys.modules:        # IDLE's shell prints the codes raw
        return False
    if "thonny" in sys.modules:         # Thonny's shell renders them; no tty
        return True
    if not hasattr(sys.stdout, "isatty") or not sys.stdout.isatty():
        return False
    if sys.platform == "win32":         # a Windows console must be asked
        try:
            import ctypes
            kernel = ctypes.windll.kernel32
            handle = kernel.GetStdHandle(-11)
            mode = ctypes.c_uint32()
            if not kernel.GetConsoleMode(handle, ctypes.byref(mode)):
                return False
            if not kernel.SetConsoleMode(handle, mode.value | 0x0004):
                return False
        except Exception:
            return False
    return True


COLOUR = _colour_works()


def tint(text, *codes):
    if not COLOUR or not text:
        return text
    return "\033[%sm%s\033[0m" % (";".join(codes), text)


VERDICT_RE = re.compile(r"^(  (?:Task|Bonus) \d+ +.*?)"
                        r"(PASS|FAIL|CRASH|TIMEOUT|MISSING|LOCKED|TOO MUCH OUTPUT)$")


def paint(report):
    """The grader's report, line by line, with its verdicts and closing
    lines in colour. The text is the server's, untouched."""
    out = []
    for line in report.split("\n"):
        m = VERDICT_RE.match(line)
        if m:
            verdict = m.group(2)
            if verdict == "LOCKED":
                line = tint(line, DIM)
            else:
                code = GREEN if verdict == "PASS" else AMBER if verdict == "MISSING" else RED
                line = m.group(1) + tint(verdict, code, BOLD)
        elif line.startswith("  HANDED IN"):
            # Amber when it did not count (too early, too late), else green.
            line = tint(line, AMBER if "does not count" in line else GREEN, BOLD)
        elif line.startswith("  Passed "):
            line = tint(line, BOLD)
        elif line.lstrip().startswith("hint:"):
            line = tint(line, CYAN)
        elif line.startswith("=") or line.startswith("-"):
            line = tint(line, DIM)
        out.append(line)
    return "\n".join(out)


def header(kind):
    title = "-- %s " % kind.capitalize()
    print()
    print(tint(title + "-" * (RULE - len(title)), BOLD))


def say(*lines):
    for line in lines:
        print(textwrap.fill(line, WIDTH, initial_indent="  ",
                            subsequent_indent="  "))


def problem(text):
    """A refusal or a failure, marked so it cannot be read as progress."""
    print(tint(textwrap.fill(" ".join(text.split()), WIDTH,
                             initial_indent="  ! ", subsequent_indent="    "),
               RED))


def plain(text):
    """Text that any shell can print: a file name or an error message may
    hold letters the shell's encoding has no room for, and a line that
    cannot be printed would be a traceback in place of the line."""
    return text.encode("ascii", "backslashreplace").decode("ascii")


class Stopped(Exception):
    """This action cannot go on: the student backed out, or the grader said no.

    Raised rather than exiting, so the menu can come back. `message` is what
    to show, None when the student simply cancelled. `maybe_arrived` marks a
    submit that got no reply at all: the one failure after which the work may
    be on the server anyway, because the reply is what went missing.
    """

    def __init__(self, message=None, maybe_arrived=False):
        Exception.__init__(self, message)
        self.message = message
        self.maybe_arrived = maybe_arrived


class KeysLater(Stopped):
    """Enter alone at a key: the keys wait for later. Before a run that is
    not the end of the check -- the tasks already open are still run and
    handed in -- and anywhere else it is a plain back-out. Not the menu's
    "skip", which leaves a task and is `skip_task`."""


# ------------------------------------------------------------
# Talking to the grader.
# ------------------------------------------------------------

# How the grader's certificate is checked: None for the machine's own
# store, or the context pinned to ISRG_ROOTS once the store has failed and
# the roots have worked, so every later request skips the failed handshake.
_trust = None


def call(method, path, token, body=None, heard=None):
    """One request. Returns (status, text). Never raises for an HTTP error.
    `heard`, when given, is a dict that is handed what a 200 said beside
    its text: under "chain", the X-Grader-Chain header or None."""
    global _trust
    request = urllib.request.Request(BASE_URL.rstrip("/") + path,
                                     data=body, method=method)
    request.add_header("Authorization", "Bearer " + token)
    request.add_header("X-Client-Version", str(CLIENT_VERSION))
    if body is not None:
        request.add_header("Content-Type", "application/json")
    try:
        try:
            return _send(request, _trust, heard)
        except urllib.error.URLError as error:
            if _trust is not None or not isinstance(
                    error.reason, ssl.SSLCertVerificationError):
                raise
            pinned = ssl.create_default_context(cadata=ISRG_ROOTS)
            try:
                reply = _send(request, pinned, heard)
            except urllib.error.HTTPError:
                _trust = pinned         # the handshake worked; the reply is real
                raise
            except urllib.error.URLError:
                raise error             # the store's verdict names the trouble
            _trust = pinned
            return reply
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode("utf-8", "replace")
    except Exception as error:
        return None, OFFLINE + " " + offline_reason(error)


def _send(request, context, heard=None):
    with urllib.request.urlopen(request, timeout=NETWORK_TIMEOUT,
                                context=context) as reply:
        if heard is not None:
            heard["chain"] = reply.headers.get("X-Grader-Chain")
        return reply.status, reply.read().decode("utf-8", "replace")


def offline_reason(error):
    """One bracketed line naming what went wrong, so a screenshot of the
    message tells the instructor whether it was DNS, a proxy, a certificate
    or a timeout -- the causes look identical to the student."""
    cause = error
    while isinstance(cause, urllib.error.URLError) and cause.reason is not None:
        cause = cause.reason
    if isinstance(cause, ssl.SSLCertVerificationError):
        return "(reason: certificate check failed: %s)" % cause.verify_message
    if isinstance(cause, ssl.SSLError):
        return "(reason: certificate check failed)"
    if isinstance(cause, socket.timeout) or type(cause).__name__ == "TimeoutError":
        return "(reason: no answer within %d seconds)" % NETWORK_TIMEOUT
    if isinstance(cause, socket.gaierror):
        return "(reason: the site's name could not be looked up)"
    if isinstance(cause, ConnectionRefusedError):
        return "(reason: connection refused)"
    text = " ".join(str(cause).split())[:80] or type(cause).__name__
    return "(reason: %s)" % text


# The code lives here and nowhere else: these variables, for as long as this
# one run lasts. Nothing is written to disk, so a lab machine keeps no trace
# of who used it -- which is the whole point.
#
# Checking may reuse a code for CODE_MEMORY_MINUTES, so an afternoon of
# checking costs one typing rather than fifteen. Handing in never reuses one:
# a submit always asks, which is what stops the next person at a shared seat
# from handing work in as whoever sat there before. The grader itself makes
# no difference between the two -- a check is stored and counts like a
# submit -- so that one question is all that separates them. The memory is idle time,
# not a session -- a student who walks away for an hour comes back to a
# prompt, and one who checks every few minutes is never asked again.
CODE_MEMORY_MINUTES = 60

_code = None
_code_at = 0.0
# How to back out of the code prompt, in the words of whichever prompt the
# student last saw, and where backing out leads. Set by ask_code and main.
_cancel = "press Cancel"
_in_menu = False


def read_token(fresh=False):
    """The code for one action -- a check or a submit -- typed or remembered.

    fresh=True always asks: that is a submit, and the point of it. Called
    once when an action begins, never per request, so how many requests an
    action happens to make cannot change how often a student types.
    """
    global _code, _code_at
    if fresh or _code is None or _forgotten():
        _code = ask_for_token(explain=True)
    else:
        say("Code: ******** (remembered from your last check)")
    _code_at = time.monotonic()
    return _code


def current_token():
    """The code the action in progress is already using.

    Asks only when there is none, which means a 401 threw the last one away
    part-way through. The expiry is not consulted here: it belongs to the
    gap between actions, not to the seconds inside one.
    """
    global _code, _code_at
    if _code is None:
        _code = ask_for_token(explain=False)
        _code_at = time.monotonic()
    return _code


def _forgotten():
    """True once the remembered code has sat unused too long."""
    return time.monotonic() - _code_at > CODE_MEMORY_MINUTES * 60


def forget_token():
    """After a 401. There is no file to delete: there never was one."""
    global _code
    _code = None


def ask_for_token(explain=True):
    """Ask for the code. An empty answer is the student backing out.

    explain=False is the retry straight after a refusal: the student read the
    explanation seconds ago, and printing it again is what buried the
    grader's reason for refusing.
    """
    if explain:
        say("Your code: 8 capitals, like K7QX2M9P. Type it exactly.",
            "No code? Get one on your PHONE at " + TOKEN_PAGE)
        print()
    token = ask_code("Type your code (it will not be shown): ")
    if not token:
        raise Stopped()
    return token


def ask_code(question):
    """Read the code without leaving it on the screen, where that is possible.

    In a terminal, getpass() does it. Thonny runs this file with a piped
    stdin, so there the terminal cannot be told to stop echoing: getpass()
    notices, warns, and echoes anyway. A tkinter window sidesteps the shell
    entirely, and Thonny is itself a tkinter app, so it is always there.
    Everything falls back to a visible prompt, because a student who cannot
    type their code at all is worse off than one whose code was on screen
    for a moment.

    A dialog leaves nothing in the shell, so what was typed is shown as stars
    there: without that line a refusal seems to answer nothing at all.

    Not on a Mac. There the window belongs to a second app called "Python"
    that cannot bring itself in front of Thonny, so the box waits unseen
    behind it until the student force-quits (seen 16 Sep 2026). The visible
    prompt in the shell is the lesser evil.
    """
    global _cancel
    _cancel = "just press Enter"
    # A real terminal hides what is typed by itself, and gets no window: on
    # WSL a Tk window can reach the taskbar and never the screen. Thonny's
    # shell claims to be a terminal and is not one: it also aliases
    # sys.__stdin__, so on Windows getpass() would read a console the
    # student cannot see and wait forever (seen 16 Sep 2026).
    if "thonny" not in sys.modules and sys.stdin.isatty():
        import getpass
        try:
            return getpass.getpass("  Code (hidden): ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            stop("I could not read your code. Run me again.")
    if sys.platform != "darwin":
        try:
            answer = code_dialog(question)
        except Exception:
            pass                    # no display: fall through to the prompt
        else:
            answer = (answer or "").strip()     # a cancelled box is an answer
            _cancel = "press Cancel"
            say("Code: " + ("********" if answer else "(cancelled)"))
            return answer
    answer = ask("  Code: ")
    print()                         # a pipe echoes no newline of its own
    return answer


def code_dialog(question):
    """A small window with one hidden field. Returns None when cancelled.

    Not the library's askstring: that hangs its box off a hidden parent
    window, and Windows then leaves it behind Thonny with nothing but a
    taskbar icon to show it exists (seen 16 Sep 2026). This window is its
    own top level, kept on top, centred and given the focus, so it is in
    front of whatever the student was looking at.
    """
    import tkinter
    root = tkinter.Tk()
    root.title("Grader")
    root.resizable(False, False)
    answer = []
    tkinter.Label(root, text=question, padx=20, pady=10).pack()
    entry = tkinter.Entry(root, show="*", width=20, font=("TkDefaultFont", 14),
                          justify="center")
    entry.pack(padx=20, pady=4)

    def ok(event=None):
        answer.append(entry.get())
        root.destroy()

    def cancel(event=None):
        root.destroy()

    row = tkinter.Frame(root)
    row.pack(pady=(10, 14))
    tkinter.Button(row, text="OK", width=8, command=ok).pack(side="left", padx=6)
    tkinter.Button(row, text="Cancel", width=8, command=cancel).pack(side="left", padx=6)
    root.bind("<Return>", ok)
    root.bind("<Escape>", cancel)
    root.protocol("WM_DELETE_WINDOW", cancel)
    root.attributes("-topmost", True)
    root.eval("tk::PlaceWindow . center")

    tries = [0]

    def to_front():
        root.deiconify()
        root.lift()
        root.focus_force()
        entry.focus_set()
        if take_keyboard(root):
            return
        tries[0] += 1
        if tries[0] < 15:               # keep at it for about two seconds
            root.after(150, to_front)
        else:
            print("  The code box is open on top of this window. Click it, "
                  "then type.")

    to_front()
    root.mainloop()
    return answer[0] if answer else None


def take_keyboard(root):
    """Windows only: make the box the window the keys go to. True when it is.

    Windows lets a program bring a window to the front only while it holds
    the "foreground right". Thonny's backend gets it when F5 starts it and
    loses it the moment the student types in Thonny's shell, which
    answering the menu does. From then on the box shows on top while every
    key still lands in the shell (seen 16 Sep 2026). Two standard remedies,
    tried in order: share the input queue of the window in front for one
    call, and, failing that, hold ALT for the call, which is Windows's own
    exception to the rule.
    """
    if sys.platform != "win32":
        return True
    try:
        import ctypes
        user32, kernel32 = ctypes.windll.user32, ctypes.windll.kernel32
        hwnd = user32.GetAncestor(root.winfo_id(), 2)       # the real window
        if user32.GetForegroundWindow() == hwnd:
            return True
        user32.SetForegroundWindow(hwnd)
        if user32.GetForegroundWindow() == hwnd:
            return True
        front = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
        mine = kernel32.GetCurrentThreadId()
        if front and front != mine and user32.AttachThreadInput(front, mine, True):
            try:
                user32.BringWindowToTop(hwnd)
                user32.SetForegroundWindow(hwnd)
                user32.SetFocus(hwnd)
            finally:
                user32.AttachThreadInput(front, mine, False)
            if user32.GetForegroundWindow() == hwnd:
                return True
        VK_MENU, KEYUP = 0x12, 0x0002
        user32.keybd_event(VK_MENU, 0, 0, 0)
        try:
            user32.SetForegroundWindow(hwnd)
        finally:
            user32.keybd_event(VK_MENU, 0, KEYUP, 0)
        return user32.GetForegroundWindow() == hwnd
    except Exception:
        return False


def ask(question):
    """input(), but a closed keyboard is a sentence rather than a traceback."""
    try:
        return input(question).strip()
    except (EOFError, KeyboardInterrupt):
        print()
        stop("I could not read your answer. Open this file in Thonny and "
             "press F5, or run it from a terminal.")


def with_token(method, path, body=None, heard=None):
    """Make a request, asking for the code again once if this one is refused."""
    token = current_token()
    status, text = call(method, path, token, body, heard)
    if status == 401:
        problem(text)
        say("Type it again, or %s to %s."
            % (_cancel, "go back to the menu" if _in_menu else "stop"))
        print()
        forget_token()
        token = current_token()
        status, text = call(method, path, token, body, heard)
    return status, text


def stop(message):
    """For the few things no menu can fix: close the program."""
    print(message)
    try:
        input("Press Enter to close.")
    except (EOFError, KeyboardInterrupt):
        pass
    sys.exit(1)


# ------------------------------------------------------------
# The two things this program does.
# ------------------------------------------------------------

def gather(plan):
    """The files in this folder the activity accepts, as base64."""
    allow = plan.get("files", {}).get("allow", [])
    limit = plan.get("files", {}).get("max_upload_bytes", 0)
    myself = os.path.basename(os.path.abspath(__file__))
    files, total, left_out = {}, 0, []
    for name in sorted(os.listdir(HERE)):
        path = os.path.join(HERE, name)
        if name == myself or not os.path.isfile(path):
            continue
        if not any(fnmatchcase(name, pattern) for pattern in allow):
            continue
        # A name the server would refuse, and the whole request with it.
        if not FILENAME_RE.match(name):
            left_out.append(plain(name))
            continue
        with open(path, "rb") as handle:
            blob = handle.read()
        total += len(blob)
        if limit and total > limit:
            raise Stopped("Your files add up to more than this activity "
                          "accepts. Remove anything that is not a task file "
                          "and try again.")
        files[name] = base64.b64encode(blob).decode("ascii")
    if left_out:
        say("Not sent: %s. The grader takes plain names like task01.py."
            % name_files(left_out))
    return files


def files_here():
    """The files beside this one, this one excepted."""
    myself = os.path.basename(os.path.abspath(__file__))
    return sorted(name for name in os.listdir(HERE)
                  if name != myself and os.path.isfile(os.path.join(HERE, name)))


def name_files(files):
    """A few names, and a count when there are more than a few."""
    if len(files) <= 4:
        return ", ".join(files)
    return "%s and %d more" % (", ".join(files[:3]), len(files) - 3)


def when(iso):
    """A server timestamp as this machine's own wall-clock time."""
    try:
        moment = datetime.datetime.fromisoformat(iso).astimezone()
        return moment.strftime("%A %d %B at %H:%M")
    except (TypeError, ValueError):
        return "later"


# The activity the files in this folder picked, as /open listed it, kept
# for the rest of this run: a second check then asks the grader one thing
# fewer. Forgotten whenever /plan or /submit says no, so an activity that
# closed or changed is picked afresh, and never kept when the student chose
# from a list, so a wrong number is not a choice for the whole run. Nothing
# rests on it: the server places every request against the timetable itself.
_picked = None


def forget_activity():
    global _picked
    _picked = None


def remembered_activity():
    """The activity picked earlier in this run, while this folder still
    holds files for it; otherwise None, and the grader is asked again."""
    if _picked is None:
        return None
    files = [name for name in files_here()
             if any(fnmatchcase(name, pattern)
                    for pattern in _picked["files"]["allow"])]
    if not files:
        forget_activity()
        return None
    say("%s: %d of your files found here." % (_picked["title"], len(files)))
    return _picked["activity"]


def pick_activity():
    """Which activity this folder is for, decided by the files in it.

    This check.py names no lab: it asks the grader what the student could
    hand in now, keeps the activities that accept a file sitting here, and
    asks the student only when more than one does. So a lab folder is a
    lab, an assignment folder is an assignment, and an empty or unrelated
    folder is a sentence rather than an upload.
    """
    global _picked
    status, text = with_token("GET", "/open")
    if status == 404:
        raise Stopped("The grader does not know this check.py yet. Tell "
                      "your instructor.")
    if status != 200:
        raise Stopped(text.strip() or OFFLINE)
    listing = json.loads(text)["open"]
    here = files_here()
    open_now = [a for a in listing if a["schedule"]["state"] == "in window"]
    matches = []
    for entry in open_now:
        files = [name for name in here
                 if any(fnmatchcase(name, pattern) for pattern in entry["files"]["allow"])]
        if files:
            matches.append((entry, files))
    if len(matches) == 1:
        entry, files = matches[0]
        say("%s: %d of your files found here." % (entry["title"], len(files)))
        _picked = entry
        return entry["activity"]
    if not matches:
        if open_now:
            wants = ["Nothing in this folder belongs to what is open, so "
                     "there is nothing to send. Run check.py from the "
                     "folder with your work."]
            for entry in open_now:
                wants.append("%s takes %s."
                             % (entry["title"], ", ".join(entry["files"]["allow"])))
            raise Stopped(" ".join(wants))
        later = sorted((a for a in listing if a["schedule"]["state"] == "not open"),
                       key=lambda a: a["schedule"]["opens"] or "")
        if later:
            raise Stopped("Nothing is open for you yet. %s opens %s."
                          % (later[0]["title"], when(later[0]["schedule"]["opens"])))
        raise Stopped("Nothing is open for you right now.")
    say("This folder has files for more than one thing.")
    for number, (entry, files) in enumerate(matches, 1):
        print("  %d  %s  (%s)" % (number, entry["title"], name_files(files)))
    while True:
        answer = ask("Type a number, or just press Enter to %s: "
                     % ("go back to the menu" if _in_menu else "stop"))
        if not answer:
            raise Stopped()
        if answer.isdigit() and 1 <= int(answer) <= len(matches):
            return matches[int(answer) - 1][0]["activity"]
        say("Please type a number from the list.")


def go(kind):
    """One check, one submit or one skip, start to finish. Raises Stopped
    if it cannot."""
    header(kind)
    # Ask here rather than inside the first request that happens to need it:
    # a submit makes two requests and must still cost exactly one typing.
    read_token(fresh=(kind == "submit"))
    activity = ACTIVITY or remembered_activity() or pick_activity()
    plan = fetch_plan(activity)
    if kind == "skip":
        skip_task(activity, plan.get("chain"))
        return

    # On an activity whose tasks open in order, the task that is next has
    # questions to answer before it opens -- asked here when the student
    # left them last time, and after the report when a task has just
    # passed. Only open tasks are run; the rest come back LOCKED.
    #
    # Enter at a key here leaves the keys for later and goes on with the
    # tasks already open, so keys never stand between a student and handing
    # in what is open. Until 28 Sep 2026 it ended the check: in Lab 05 a
    # student with eight tasks passed and Task 9's keys wrong could hand
    # nothing in, check or submit, until the keys were right.
    chain = plan.get("chain")
    tasks = plan["tasks"]
    keys_later = False
    if chain:
        if chain["next"]:
            if chain["open"]:
                enter = "%s your open tasks now" % (
                    "hand in" if kind == "submit" else "check")
            else:
                enter = "go back to the menu"
            try:
                if ask_questions(activity, chain, enter):
                    chain["open"] = chain["next"]["number"]
            except KeysLater:
                if not chain["open"]:
                    raise Stopped()     # nothing is open to check without them
                keys_later = True
        tasks = tasks[:chain["open"]]
        if not tasks:
            raise Stopped("Nothing is open yet: Task 01 opens once its "
                          "questions are answered.")

    runner = plan["runner"]
    cap = runner["output_cap_kb"] * 1024
    if chain:
        sys.stdout.write("  Running %d of %d tasks (the rest are locked) ... "
                         % (len(tasks), chain["of"]))
    else:
        sys.stdout.write("  Running %d task files ... " % len(tasks))
    sys.stdout.flush()
    runs = [run_task(HERE, task["file"], task.get("stdin", ""),
                     runner["timeout_seconds"], cap, task.get("shell"),
                     plan.get("harness"), task.get("watch"))
            for task in tasks]
    print(tint("done", GREEN))

    body = json.dumps({"format": FORMAT, "activity": activity, "kind": kind,
                       "files": gather(plan), "runs": runs,
                       "client": client_block()}).encode("utf-8")
    heard = {}
    status, text = with_token("POST", "/submit", body, heard)
    if status != 200:
        forget_activity()
        raise Stopped(text.strip() or OFFLINE,
                      maybe_arrived=(kind == "submit" and status is None))
    print()
    sys.stdout.write(paint(text))
    # Keys just left for later are not asked again a minute on.
    if chain and not keys_later:
        after_report(activity, chain_beside(heard))


def client_block():
    """What this copy says of itself with a hand-in and with an answer to a
    key: its version, Python's, the platform, and where it ran."""
    return dict(ran_on(), version=CLIENT_VERSION,
                python="%d.%d.%d" % sys.version_info[:3],
                platform=sys.platform)


def ran_on():
    """The account and the computer this ran on, as each names itself: what
    the instructors' board shows beside a hand-in. Nothing here or on the
    server is decided by either, and one that cannot be read is left out."""
    said = {}
    try:
        import getpass
        said["account"] = getpass.getuser()
    except Exception:
        pass
    try:
        said["computer"] = socket.gethostname()
    except Exception:
        pass
    return said


def fetch_plan(activity):
    status, text = with_token("GET", "/plan?activity=" + activity)
    if status != 200:
        forget_activity()
        raise Stopped(text.strip() or OFFLINE)
    return json.loads(text)


def chain_beside(heard):
    """Where the chain stands now that the work is handed in, as the grader
    said it beside the receipt: what /plan would send under "chain". None
    when it sent nothing of the kind -- a grader from before it did, or a
    chain too long for a header -- and then /plan is asked, as before."""
    try:
        chain = json.loads(heard.get("chain") or "")
    except ValueError:
        return None
    return chain if isinstance(chain, dict) else None


def after_report(activity, chain=None):
    """Once the report is printed on a chained activity: the next task's
    questions when one has just passed. The work above is handed in
    already, so backing out here only goes back to the menu. `chain` is
    where the chain stands when the receipt's reply said; the grader is
    asked when it did not. Either way it only picks what to ask next: the
    grader judges every key and locks every task itself. A task that did
    not pass is left to the menu's "skip": nothing is offered here."""
    try:
        if chain is None:
            chain = fetch_plan(activity).get("chain") or {}
        if chain.get("next"):
            print()
            ask_questions(activity, chain)
    except Stopped as stopped:
        if stopped.message:
            problem(stopped.message)


def ask_questions(activity, chain, enter="go back to the menu"):
    """Ask the next task's keys, one at a time, each judged by the grader.
    The lab sheet holds the question; here a key is named by its number
    only, Key 3.2 being the second key of Task 3. Returns True once the
    task is open. An empty answer raises KeysLater, and `enter` says in the
    prompt what that leads to; what was answered right stays answered."""
    block = chain["next"]
    number, title = block["number"], block["title"]
    pending = [(i, q) for i, q in enumerate(block["questions"], 1)
               if not q.get("done")]
    if not pending:
        return True
    left = len(pending)
    if left == len(block["questions"]):
        what = "its %d keys" % left if left > 1 else "its key"
    else:
        what = "its %d remaining keys" % left if left > 1 else "its last key"
    say('Task %02d "%s" is locked. Answer %s to open it. Press Enter '
        'without typing anything to %s.'
        % (number, title, what, enter))
    opened = False
    for index, question in pending:
        choices = question.get("choices") or []
        label = "Key %d.%d" % (number, index)
        while True:
            if choices:
                print("  " + tint(label, BOLD))
                for n, choice in enumerate(choices, 1):
                    print("      %s  %s" % (tint(str(n), BOLD), choice))
                typed = ask("      Type a number: ")
                if not typed:
                    raise KeysLater()
                if not (typed.isdigit() and 1 <= int(typed) <= len(choices)):
                    say("Please type a number from 1 to %d." % len(choices))
                    continue
                given = choices[int(typed) - 1]
            else:
                given = ask("  %s: " % label)
                if not given:
                    raise KeysLater()
            reply = judge(activity, number, index, given)
            if reply["correct"]:
                print("  " + tint("Right.", GREEN, BOLD))
                break
            # The hint, then the key again. Its number is the whole prompt,
            # so a run of misses never pushes the question off the screen.
            print("  " + tint("Not quite.", RED, BOLD) + " " + reply["hint"])
        opened = reply["opened"]
    if opened:
        print()
        say("Task %02d is open. Do it, then check again." % number)
    return opened


def judge(activity, number, index, given):
    body = json.dumps({"format": FORMAT, "activity": activity, "task": number,
                       "question": index, "answer": given,
                       "client": client_block()}).encode("utf-8")
    status, text = with_token("POST", "/answer", body)
    if status != 200:
        raise Stopped(text.strip() or OFFLINE)
    return json.loads(text)


def skip_task(activity, chain):
    """The menu's "skip": leave the task the student is on for now. Nothing
    has to be run or waited for first. The task stays open and counts when
    it passes, and the next task's keys are asked as after a pass. Whether
    a task may be skipped, and how many skips are left, is the grader's to
    say: this asks once, since a skip is not given back, and sends it."""
    if not chain:
        raise Stopped("There is nothing to skip here: every task is open "
                      "from the start.")
    if chain.get("next"):
        # The task they are at is behind its keys, and a key is never
        # skipped: ask them, as a check would.
        say("Task %02d is still locked, and only an open task can be "
            "skipped." % chain["next"]["number"])
        print()
        ask_questions(activity, chain)
        return
    block = chain.get("move_on")
    if not block:
        on = chain.get("open", 0)
        if on == chain.get("of"):
            raise Stopped("Task %02d is the last task: there is nothing "
                          "after it to skip to." % on)
        raise Stopped("You have no skips left here: Task %02d opens once "
                      "Task %02d passes." % (on + 1, on))
    number = block["number"]
    left = block.get("left", 0)
    say("Skip Task %02d for now? It stays open and counts as soon as it "
        "passes. %s Type y to skip it, or press Enter without typing "
        "anything to %s."
        % (number,
           "This is your last skip here." if left == 1
           else "You have %d skips left here, and this uses one." % left,
           "go back to the menu" if _in_menu else "stop"))
    if ask("      y or Enter: ").lower() not in ("y", "yes"):
        raise Stopped()
    body = json.dumps({"format": FORMAT, "activity": activity,
                       "task": number}).encode("utf-8")
    status, text = with_token("POST", "/move-on", body)
    if status != 200:
        raise Stopped(text.strip() or OFFLINE)
    print()
    say("Task %02d is skipped. It stays open and counts when it passes."
        % number)
    # The skip is recorded: whatever stops the keys below, it stands.
    try:
        chain = fetch_plan(activity).get("chain") or {}
        if chain.get("next"):
            print()
            ask_questions(activity, chain)
        elif chain.get("open", 0) > number:
            say("Task %02d is open. Do it, then check again."
                % chain["open"])
    except Stopped as stopped:
        if stopped.message:
            problem(stopped.message)


def finish(kind, stopped, in_menu):
    """What a student reads when an action could not finish."""
    if stopped.message:
        problem(stopped.message)
    back = " Back to the menu." if in_menu else ""
    if stopped.maybe_arrived:
        say("It may have arrived anyway. Submit again once the grader "
            "answers: an extra submission does no harm." + back)
    else:
        say("Nothing was %s.%s"
            % ({"submit": "handed in", "skip": "skipped"}.get(kind, "checked"),
               back))


def unexpected(error):
    """An error nothing above was written for: a file another program holds
    locked, a reply that is not the grader's, a task that could not be
    started. One line naming it, where a traceback would take the menu and
    the remembered code away with it."""
    forget_activity()
    detail = " ".join(plain(str(error)).split())[:80]
    problem("Something went wrong (%s%s). Your files are unchanged; try "
            "again." % (type(error).__name__, ": " + detail if detail else ""))


def choose():
    """No arguments: ask, so pressing F5 in Thonny is enough.

    Returns None for "I am done", which ends the run.
    """
    print(tint("What would you like to do?", BOLD))
    print("  %s  check    mark my work (your code is remembered)" % tint("1", BOLD))
    print("  %s  submit   hand my work in (asks for your code again)" % tint("2", BOLD))
    print("  %s  skip     leave the task I am on for now" % tint("3", BOLD))
    print("  %s  quit" % tint("4", BOLD))
    while True:
        answer = ask("Type 1, 2, 3 or 4 and press Enter: ")
        if answer in ("1", "check"):
            return "check"
        if answer in ("2", "submit"):
            return "submit"
        if answer in ("3", "skip"):
            return "skip"
        if answer in ("4", "quit"):
            return None
        say("Please type 1, 2, 3 or 4.")


def main():
    global _in_menu
    if not BASE_URL:
        stop("This check.py was not set up: it does not know where the "
             "grader is. Download the one on the grader's page, or ask "
             "your instructor for it.")
    for kind in ("check", "submit", "skip"):
        if "--" + kind in sys.argv:
            try:
                go(kind)
            except Stopped as stopped:
                finish(kind, stopped, in_menu=False)
                sys.exit(1)
            except Exception as error:      # not Ctrl-C, not sys.exit
                unexpected(error)
                sys.exit(1)
            return
    # The menu comes back after every report, and after anything that stopped
    # an action part-way: a wrong code or a dropped network is something to
    # try again, not a reason to make a student find F5 a second time. One
    # run of this program is the whole lab, not one check of it.
    _in_menu = True
    while True:
        kind = choose()
        if kind is None:
            return
        try:
            go(kind)
        except Stopped as stopped:
            finish(kind, stopped, in_menu=True)
        except Exception as error:          # not Ctrl-C, not sys.exit
            unexpected(error)
        print()


if __name__ == "__main__":
    main()
