"""Optional deterministic coding test execution (Python only).

Restricted: no network, short timeout, no builtins that open files/network.
Not a full sandbox — Platform should still treat untrusted code carefully.
"""

from __future__ import annotations

import ast
import signal
import threading
from typing import Any, Callable


_BLOCKED_NAMES = frozenset(
    {
        "open",
        "exec",
        "eval",
        "compile",
        "__import__",
        "input",
        "breakpoint",
        "exit",
        "quit",
        "help",
        "memoryview",
    }
)


class _Timeout(Exception):
    pass


def _on_alarm(_signum, _frame):  # noqa: ANN001
    raise _Timeout("execution timed out")


def _run_with_timeout(fn: Callable[[], Any], timeout_seconds: float) -> Any:
    """Best-effort timeout. SIGALRM only works on the main thread."""
    use_alarm = (
        hasattr(signal, "SIGALRM")
        and threading.current_thread() is threading.main_thread()
    )
    if not use_alarm:
        return fn()
    prev = signal.signal(signal.SIGALRM, _on_alarm)
    signal.setitimer(signal.ITIMER_REAL, timeout_seconds)
    try:
        return fn()
    finally:
        signal.setitimer(signal.ITIMER_REAL, 0)
        signal.signal(signal.SIGALRM, prev)


def _safe_builtins() -> dict[str, Any]:
    import builtins as _b

    allowed = {
        "abs",
        "all",
        "any",
        "bool",
        "dict",
        "enumerate",
        "float",
        "frozenset",
        "int",
        "len",
        "list",
        "max",
        "min",
        "pow",
        "print",
        "range",
        "reversed",
        "round",
        "set",
        "sorted",
        "str",
        "sum",
        "tuple",
        "zip",
        "True",
        "False",
        "None",
        "Exception",
        "ValueError",
        "TypeError",
        "KeyError",
        "IndexError",
        "RuntimeError",
    }
    out: dict[str, Any] = {}
    for name in allowed:
        if hasattr(_b, name):
            out[name] = getattr(_b, name)
    out["__build_class__"] = _b.__build_class__
    out["__name__"] = "__candidate__"
    return out


def _validate_ast(source: str) -> None:
    tree = ast.parse(source)
    for node in ast.walk(tree):
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            raise ValueError("imports are not allowed in executed submissions")
        if isinstance(node, ast.Attribute) and node.attr.startswith("__"):
            raise ValueError("dunder attribute access is not allowed")
        if isinstance(node, ast.Name) and node.id in _BLOCKED_NAMES:
            raise ValueError(f"use of `{node.id}` is not allowed")
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
            if node.func.id in _BLOCKED_NAMES:
                raise ValueError(f"call to `{node.func.id}` is not allowed")


def _call_entry(ns: dict[str, Any], args: Any) -> Any:
    """Prefer an obvious function: solve/solution/main/add/first def."""
    for name in ("solve", "solution", "main", "answer", "run"):
        fn = ns.get(name)
        if callable(fn):
            if isinstance(args, dict):
                return fn(**args)
            if isinstance(args, (list, tuple)):
                return fn(*args)
            if args is None:
                return fn()
            return fn(args)
    # First user-defined function
    for name, val in ns.items():
        if callable(val) and not name.startswith("_") and name not in ("print",):
            if isinstance(args, dict):
                return val(**args)
            if isinstance(args, (list, tuple)):
                return val(*args)
            if args is None:
                return val()
            return val(args)
    raise RuntimeError("no callable entrypoint found (define solve/solution/main)")


def _normalize_expected(case: dict[str, Any]) -> Any:
    if "expected" in case:
        return case["expected"]
    if "output" in case:
        return case["output"]
    if "expected_output" in case:
        return case["expected_output"]
    return None


def _normalize_args(case: dict[str, Any]) -> Any:
    if "args" in case:
        return case["args"]
    if "input" in case:
        return case["input"]
    if "stdin" in case:
        return case["stdin"]
    return None


def run_python_tests(
    code: str,
    test_cases: list[dict[str, Any]],
    *,
    timeout_seconds: float = 2.0,
) -> tuple[list[dict[str, Any]], float, list[str]]:
    """Execute test_cases against candidate Python code.

    Returns (results, pass_ratio, failing_names).
    """
    if not test_cases:
        return [], 0.0, []

    try:
        _validate_ast(code)
    except Exception as exc:  # noqa: BLE001
        results = [
            {
                "name": str(c.get("name") or f"case_{i + 1}"),
                "passed": False,
                "expected": _normalize_expected(c),
                "actual": None,
                "error": f"validation: {exc}",
            }
            for i, c in enumerate(test_cases)
        ]
        return results, 0.0, [r["name"] for r in results]

    results: list[dict[str, Any]] = []
    failing: list[str] = []
    passed_n = 0

    for i, case in enumerate(test_cases):
        name = str(case.get("name") or f"case_{i + 1}")
        expected = _normalize_expected(case)
        args = _normalize_args(case)
        try:
            ns: dict[str, Any] = {"__builtins__": _safe_builtins()}

            def _run() -> Any:
                exec(compile(code, "<candidate>", "exec"), ns, ns)  # noqa: S102
                return _call_entry(ns, args)

            actual = _run_with_timeout(_run, timeout_seconds)
            ok = actual == expected
            if ok:
                passed_n += 1
            else:
                failing.append(name)
            results.append(
                {
                    "name": name,
                    "passed": ok,
                    "expected": expected,
                    "actual": actual,
                    "error": None if ok else "assertion failed",
                }
            )
        except Exception as exc:  # noqa: BLE001
            failing.append(name)
            results.append(
                {
                    "name": name,
                    "passed": False,
                    "expected": expected,
                    "actual": None,
                    "error": str(exc),
                }
            )

    ratio = passed_n / len(test_cases) if test_cases else 0.0
    return results, ratio, failing
