"""
The tester: runs a student's code against a question part's tests and reports what happened.

The same file runs in two places:
- in the student's browser, inside Pyodide in a Web Worker (app/static/runner.js loads it), and
- on the engineer's machine, in CPython, through plans/tools/run_tests.py, which checks every typed tester
  against the course staff's official solution.

It never touches the network, and the disk only in a temporary folder holding the files a test declares. Everything it returns is plain
data (dicts, lists, strings), so the browser can send it to the tutor as it is.

A part's tests (the `tests` field of a part in plans/exams/<exam>.json) look like this:

    {"mode": "function",            # "function": call the student's functions; "output": run a whole program
     "setup": "",                   # Python run before the student's code (imports, data); may be empty
     "needs": ["digit_sum"],        # functions the student must define (the part's own and any it relies on)
     "files": {"data.csv": "..."},  # files the code may open (written to a temporary folder)
     "stdin": "",                   # what input() reads, line by line ("output" and "program" modes)
     "cases": [{"code": "lst = [3, 1, 2]",      # optional statements run first, in the student's namespace
                "call": "digit_sum(247)",       # an expression; its value is compared with `expect`
                "expect": "13",                 # a Python expression for the expected value
                "note_he": "הדוגמה מהשאלה"}],   # optional, shown beside the case
     "program": "...",              # "output" mode: the program whose printed output the student predicts
     "expect_stdout": "...",        # "output" mode: what the program prints (checked against a real run)
     "limits": {"recursive": "digit_sum", "no_loops": true, "allowed": [...], "no_dict": true}}

In "output" mode the student's answer is their predicted output (text), not code: the harness runs the program
itself and compares line by line, ignoring trailing spaces and blank lines at the end.
"""
import ast
import builtins
import io
import math
import os
import shutil
import sys
import tempfile
import traceback

os.environ.setdefault("MPLBACKEND", "Agg")   # plt.show() draws nothing and never blocks
import warnings  # noqa: E402

warnings.filterwarnings("ignore")             # library warnings are not the student's output

STEP_BUDGET = 3_000_000          # lines executed before we call it an endless loop
MAX_OUT = 20_000                 # characters of printed output kept per run
SHORT = 300                      # characters of a value shown in a report
OWN_FILES = {"<code>", "<student>", "<program>", "<setup>", "<test>"}   # the file names compile() gives our code

# Names every Python program may use without them counting as "built-in functions" in the exam's sense.
ALWAYS_OK = {"print", "input", "range", "len", "True", "False", "None", "int", "str", "float", "bool", "list",
             "tuple", "isinstance", "type", "super", "object", "Exception", "ValueError", "TypeError",
             "IndexError", "KeyError", "ZeroDivisionError", "AssertionError", "StopIteration", "RecursionError"}


class StepLimit(Exception):
    pass


def _short(v):
    try:
        s = repr(v)
    except Exception:  # noqa: BLE001
        s = "<value that cannot be shown>"
    return s if len(s) <= SHORT else s[:SHORT] + "…"


def _equal(a, b):
    if isinstance(a, bool) or isinstance(b, bool):
        return type(a) is type(b) and a == b
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        if isinstance(a, float) or isinstance(b, float):
            return math.isclose(a, b, rel_tol=1e-6, abs_tol=1e-9)
        return a == b
    if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
        return type(a) is type(b) and len(a) == len(b) and all(_equal(x, y) for x, y in zip(a, b))
    try:
        return type(a) is type(b) and bool(a == b)
    except Exception:  # noqa: BLE001
        return False


class _Files:
    """The test's files as real files in a fresh temporary folder, which is the current folder while the code runs.
    So open(), pandas.read_csv() and anything else that reads a file see exactly these files, in the browser
    (Pyodide's in-memory disk) and in CPython alike. The folder is removed afterwards."""

    def __init__(self, files):
        self.files = dict(files or {})
        self.dir = None
        self.old = None

    def __enter__(self):
        self.dir = tempfile.mkdtemp(prefix="run-")
        for name, body in self.files.items():
            path = os.path.join(self.dir, os.path.basename(str(name)))
            with open(path, "w", encoding="utf-8") as f:
                f.write(body)
        self.old = os.getcwd()
        os.chdir(self.dir)
        return self

    def __exit__(self, *exc):
        try:
            os.chdir(self.old)
        finally:
            shutil.rmtree(self.dir, ignore_errors=True)
        return False


class _Run:
    """One sandboxed run: captured output, scripted input, virtual files, a step budget."""

    def __init__(self, stdin=""):
        self.out = io.StringIO()
        self.lines = (stdin or "").splitlines()
        self.steps = 0

    def _input(self, prompt=""):
        self.out.write(str(prompt))
        if not self.lines:
            raise EOFError("input() was called but the test gives no more input")
        line = self.lines.pop(0)
        self.out.write(line + "\n")
        return line

    def _print(self, *args, sep=" ", end="\n", file=None, flush=False):
        if file is not None and file is not sys.stdout:
            return builtins.print(*args, sep=sep, end=end, file=file)
        if self.out.tell() < MAX_OUT:
            self.out.write(sep.join(str(a) for a in args) + end)

    def _trace(self, frame, event, arg):
        # Only the code being tested is counted and traced: library code (pandas, matplotlib) runs untraced, at
        # full speed. An endless loop inside a library is stopped by the browser's time limit (runner.js).
        if event == "call":
            return self._trace if frame.f_code.co_filename in OWN_FILES else None
        if event == "line":
            self.steps += 1
            if self.steps > STEP_BUDGET:
                raise StepLimit()
        return self._trace

    def namespace(self):
        b = dict(vars(builtins))
        b.update(print=self._print, input=self._input)
        return {"__name__": "__main__", "__builtins__": b}

    def execute(self, src, ns, filename="<code>"):
        code = compile(src, filename, "exec")
        old = sys.gettrace()
        sys.settrace(self._trace)
        try:
            exec(code, ns)  # noqa: S102 - this is the sandboxed runner's whole purpose
        finally:
            sys.settrace(old)

    def evaluate(self, expr, ns):
        code = compile(expr, "<test>", "eval")
        old = sys.gettrace()
        sys.settrace(self._trace)
        try:
            return eval(code, ns)  # noqa: S307
        finally:
            sys.settrace(old)


def _error(e, filename="<code>"):
    """A short, student-readable description of an exception: its type, message and the line in their code."""
    if isinstance(e, StepLimit):
        return {"type": "StepLimit", "message": "the code ran too long (an endless loop?)", "line": None}
    if isinstance(e, RecursionError):
        return {"type": "RecursionError", "message": "maximum recursion depth exceeded (a missing base case?)",
                "line": None}
    line = None
    if isinstance(e, SyntaxError):
        return {"type": "SyntaxError", "message": e.msg, "line": e.lineno, "text": (e.text or "").rstrip()}
    tb = traceback.extract_tb(e.__traceback__)
    for fr in reversed(tb):
        if fr.filename == filename:
            line = fr.lineno
            break
    return {"type": type(e).__name__, "message": str(e)[:SHORT], "line": line}


# ---------------------------------------------------------------- rules of the exam


def check_rules(code, limits=None):
    """Static checks of the course's rules: built-ins outside the exam's table, dict, global, imports, loops,
    recursion. Returns a list of {rule, line, message}. These are warnings for the student, not test failures."""
    limits = limits or {}
    out = []
    try:
        tree = ast.parse(code)
    except SyntaxError:
        return out
    allowed = set(limits.get("allowed") or []) | ALWAYS_OK
    defined = {n.name for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.ClassDef))}
    assigned = {t.id for n in ast.walk(tree) if isinstance(n, (ast.Assign, ast.AugAssign, ast.For, ast.AnnAssign))
                for t in ast.walk(n.target if hasattr(n, "target") else n.targets[0]) if isinstance(t, ast.Name)}
    params = {a.arg for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) for a in n.args.args}
    builtin_names = set(dir(builtins))
    has_loop = False
    for n in ast.walk(tree):
        if isinstance(n, (ast.For, ast.While, ast.ListComp, ast.GeneratorExp, ast.SetComp, ast.DictComp)):
            has_loop = True
            if limits.get("no_loops"):
                out.append({"rule": "no_loops", "line": n.lineno, "message": "loop"})
        if isinstance(n, ast.Global):
            out.append({"rule": "no_globals", "line": n.lineno, "message": "global " + ", ".join(n.names)})
        if limits.get("no_dict", True) and (isinstance(n, (ast.Dict, ast.DictComp)) or
                                            (isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
                                             and n.func.id == "dict")):
            out.append({"rule": "no_dict", "line": n.lineno, "message": "dict"})
        if isinstance(n, (ast.Import, ast.ImportFrom)) and not limits.get("imports_ok"):
            names = [a.name for a in n.names] if isinstance(n, ast.Import) else [n.module or ""]
            out.append({"rule": "import", "line": n.lineno, "message": "import " + ", ".join(names)})
        if limits.get("allowed") is not None and isinstance(n, ast.Call):
            f = n.func
            if isinstance(f, ast.Name) and f.id in builtin_names and f.id not in allowed \
                    and f.id not in defined and f.id not in assigned and f.id not in params:
                out.append({"rule": "builtin", "line": n.lineno, "message": f.id + "()"})
            elif isinstance(f, ast.Attribute) and f.attr in _COMMON_METHODS and f.attr not in allowed:
                # a method call such as lst.index(x) or s.split() that the exam's table does not list
                out.append({"rule": "builtin", "line": n.lineno, "message": "." + f.attr + "()"})
    rec = limits.get("recursive")
    if rec:
        fn = next((n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == rec), None)
        if fn is not None and not any(isinstance(c, ast.Call) and isinstance(c.func, ast.Name) and c.func.id == rec
                                      for c in ast.walk(fn)):
            out.append({"rule": "recursive", "line": fn.lineno, "message": rec + " does not call itself"})
    seen, uniq = set(), []
    for r in out:
        k = (r["rule"], r["line"], r["message"])
        if k not in seen:
            seen.add(k)
            uniq.append(r)
    return uniq


_COMMON_METHODS = {"index", "count", "find", "rfind", "split", "join", "strip", "lstrip", "rstrip", "replace",
                   "upper", "lower", "isdigit", "isalpha", "isupper", "islower", "startswith", "endswith", "pop",
                   "insert", "remove", "reverse", "sort", "copy", "clear", "append", "extend", "keys", "values",
                   "items", "get", "format", "title", "capitalize", "swapcase", "zfill", "center", "isspace",
                   "isalnum", "splitlines", "partition"}


# ---------------------------------------------------------------- running


def run_code(code, stdin="", files=None):
    """Run free code (the student pressed "run" with no tests): returns its output and any error."""
    with _Files(files):
        return _run_code(code, stdin)


def _run_code(code, stdin=""):
    r = _Run(stdin)
    ns = r.namespace()
    err = None
    try:
        r.execute(code, ns, "<student>")
    except BaseException as e:  # noqa: BLE001
        err = _error(e, "<student>")
    return {"kind": "run", "stdout": r.out.getvalue(), "error": err, "steps": r.steps}


def _norm_lines(s):
    lines = [ln.rstrip() for ln in (s or "").replace("\r\n", "\n").split("\n")]
    while lines and not lines[-1]:
        lines.pop()
    while lines and not lines[0]:
        lines.pop(0)
    return lines


def run_output(answer, tests):
    """"What is printed?" parts: run the program, compare its output with the student's predicted answer."""
    with _Files(tests.get("files")):
        return _run_output(answer, tests)


def _run_output(answer, tests):
    r = _Run(tests.get("stdin", ""))
    ns = r.namespace()
    err = None
    try:
        if tests.get("setup"):
            r.execute(tests["setup"], ns, "<setup>")
        r.execute(tests.get("program", ""), ns, "<program>")
    except BaseException as e:  # noqa: BLE001
        err = _error(e, "<program>")
    real = _norm_lines(r.out.getvalue())
    mine = _norm_lines(answer)
    rows = []
    for i in range(max(len(real), len(mine))):
        a = real[i] if i < len(real) else None
        b = mine[i] if i < len(mine) else None
        rows.append({"line": i + 1, "expected": a, "got": b,
                     "ok": a is not None and b is not None and a.strip() == b.strip()})
    passed = sum(r_["ok"] for r_ in rows)
    return {"kind": "output", "passed": passed, "total": len(real), "ok": passed == len(real) == len(mine) and not err,
            "lines": rows, "program_error": err}


def run_tests(code, tests, reveal=True):
    """Run the student's code against a part's tests. Returns a report the browser shows and the tutor reads."""
    mode = tests.get("mode", "function")
    if mode == "output":
        return run_output(code, tests)
    with _Files(tests.get("files")):
        return _run_tests(code, tests, mode, reveal)


def _run_tests(code, tests, mode, reveal):
    r = _Run(tests.get("stdin", ""))
    ns = r.namespace()
    report = {"kind": "tests", "mode": mode, "cases": [], "passed": 0, "total": len(tests.get("cases") or []),
              "load_error": None, "missing": [], "rules": check_rules(code, tests.get("limits")),
              "stdout": ""}
    try:
        if tests.get("setup"):
            r.execute(tests["setup"], ns, "<setup>")
        r.execute(code, ns, "<student>")
    except BaseException as e:  # noqa: BLE001
        report["load_error"] = _error(e, "<student>")
        report["stdout"] = r.out.getvalue()[:2000]
        report["ok"] = False
        return report
    report["missing"] = [n for n in (tests.get("needs") or []) if not callable(ns.get(n))]
    load_out = r.out.getvalue()
    for i, case in enumerate(tests.get("cases") or []):
        row = {"n": i + 1, "call": case.get("call", ""), "note_he": case.get("note_he", "")}
        if case.get("code"):
            row["code"] = case["code"]
        local = dict(ns)
        r.out = io.StringIO()
        r.steps = 0
        try:
            if case.get("code"):
                r.execute(case["code"], local, "<test>")
            got = r.evaluate(case["call"], local) if case.get("call") else None
            want = eval(case["expect"], {"__builtins__": builtins}) if "expect" in case else None  # noqa: S307
            if "expect_stdout" in case:
                ok = _norm_lines(r.out.getvalue()) == _norm_lines(case["expect_stdout"])
                row.update(got=r.out.getvalue()[:SHORT], expected=case["expect_stdout"][:SHORT])
            else:
                ok = _equal(got, want)
                row.update(got=_short(got), expected=_short(want))
            row["ok"] = bool(ok)
        except BaseException as e:  # noqa: BLE001
            row["ok"] = False
            row["error"] = _error(e, "<student>")
        out = r.out.getvalue()
        if out and "expect_stdout" not in case:
            row["stdout"] = out[:SHORT]
        if not reveal and not row["ok"]:
            row.pop("expected", None)
        report["cases"].append(row)
        report["passed"] += row["ok"]
    report["stdout"] = load_out[:2000]
    report["ok"] = report["passed"] == report["total"] and not report["missing"]
    return report


def run(request):
    """Entry point for the browser worker: request = {action, code, tests?, stdin?, files?}."""
    sys.setrecursionlimit(3000)
    action = request.get("action")
    if action == "tests":
        return run_tests(request.get("code", ""), request.get("tests") or {})
    if action == "rules":
        return {"kind": "rules", "rules": check_rules(request.get("code", ""), request.get("limits"))}
    return run_code(request.get("code", ""), request.get("stdin", ""), request.get("files"))
