"""Filtro conservador de sintaxis para tareas locales de cálculo y programación.

Reduce el alcance de lo que se ejecuta; NO es una barrera de seguridad ni
sustituye namespaces, seccomp y límites del sandbox. Los rechazos son una
categoría observada y pueden incluir programas benignos fuera del subconjunto.
"""
import ast

MODULES = {'math','itertools','functools','collections','fractions','decimal',
           'statistics','heapq','bisect','string','re'}
MODULE_ATTRS = {
 'math':set('ceil floor factorial gcd lcm sqrt isqrt log log2 log10 exp sin cos tan asin acos atan atan2 pi e tau inf isnan isinf isfinite trunc fabs copysign prod comb perm dist hypot fsum degrees radians'.split()),
 'itertools':set('accumulate chain combinations combinations_with_replacement compress count cycle dropwhile filterfalse groupby islice pairwise permutations product repeat starmap takewhile tee zip_longest'.split()),
 'functools':set('reduce lru_cache cache partial cmp_to_key'.split()),
 'collections':set('Counter defaultdict deque namedtuple OrderedDict'.split()),
 'fractions':{'Fraction'},'decimal':{'Decimal','ROUND_HALF_UP','ROUND_HALF_EVEN','localcontext'},
 'statistics':set('mean median mode multimode pstdev pvariance stdev variance quantiles'.split()),
 'heapq':set('heapify heappush heappop heappushpop heapreplace nlargest nsmallest merge'.split()),
 'bisect':set('bisect bisect_left bisect_right insort insort_left insort_right'.split()),
 'string':set('ascii_letters ascii_lowercase ascii_uppercase digits hexdigits octdigits punctuation whitespace'.split()),
 're':set('match fullmatch search findall finditer sub subn split escape IGNORECASE MULTILINE DOTALL'.split()),
}
SAFE_BUILTINS = {'abs','all','any','bool','chr','complex','dict','divmod','enumerate',
                 'filter','float','int','isinstance','len','list','map','max','min',
                 'next','ord','pow','print','range','repr','reversed','round','set',
                 'slice','sorted','str','sum','tuple','type','zip','ValueError',
                 'TypeError','IndexError','KeyError','ZeroDivisionError','Exception'}
FORBIDDEN_NAMES = {'open','input','eval','exec','compile','__import__','getattr','setattr',
                   'delattr','hasattr','globals','locals','vars','dir','help','breakpoint',
                   'memoryview','classmethod','staticmethod','super','object'}
METHODS = {'append','extend','insert','pop','remove','clear','copy','count','index','sort',
           'reverse','add','discard','difference','difference_update','intersection',
           'intersection_update','union','update','issubset','issuperset','get','items',
           'keys','values','setdefault','split','rsplit','splitlines','join','strip','lstrip',
           'rstrip','replace','lower','upper','capitalize','title','swapcase','casefold',
           'startswith','endswith','find','rfind','isalpha','isalnum','isdigit','isdecimal',
           'islower','isupper','isspace','partition','rpartition','zfill','ljust','rjust',
           'center','encode','decode','bit_count','bit_length','as_integer_ratio'}
NODES = {ast.Module,ast.Expr,ast.Assign,ast.AnnAssign,ast.AugAssign,ast.NamedExpr,ast.Name,
         ast.Load,ast.Store,ast.Del,ast.Constant,ast.BinOp,ast.UnaryOp,ast.BoolOp,ast.Compare,
         ast.Add,ast.Sub,ast.Mult,ast.Div,ast.FloorDiv,ast.Mod,ast.Pow,ast.MatMult,ast.BitAnd,
         ast.BitOr,ast.BitXor,ast.LShift,ast.RShift,ast.UAdd,ast.USub,ast.Not,ast.Invert,
         ast.And,ast.Or,ast.Eq,ast.NotEq,ast.Lt,ast.LtE,ast.Gt,ast.GtE,ast.Is,ast.IsNot,
         ast.In,ast.NotIn,ast.If,ast.IfExp,ast.For,ast.While,ast.Break,ast.Continue,ast.Pass,
         ast.FunctionDef,ast.Lambda,ast.arguments,ast.arg,ast.Return,ast.Call,ast.keyword,
         ast.List,ast.Tuple,ast.Set,ast.Dict,ast.Subscript,ast.Slice,ast.Starred,ast.ListComp,
         ast.SetComp,ast.DictComp,ast.GeneratorExp,ast.comprehension,ast.Attribute,ast.Import,
         ast.ImportFrom,ast.alias,ast.Assert,ast.Try,ast.ExceptHandler,ast.Raise,ast.JoinedStr,
         ast.FormattedValue,ast.Delete}


def check_pure(code):
    """Devuelve (permitido, motivo) sin ejecutar ni importar el programa."""
    try: tree=ast.parse(code)
    except SyntaxError as exc:return False, f'syntax: {exc.msg}'
    bound=set(SAFE_BUILTINS)
    for node in ast.walk(tree):
        if isinstance(node,ast.Name) and isinstance(node.ctx,(ast.Store,ast.Del)):bound.add(node.id)
        if isinstance(node,ast.FunctionDef):bound.add(node.name)
        if isinstance(node,ast.arg):bound.add(node.arg)
        if isinstance(node,ast.ExceptHandler) and node.name:bound.add(node.name)
        if isinstance(node,(ast.Import,ast.ImportFrom)):
            bound.update(alias.asname or alias.name for alias in node.names)
    for node in ast.walk(tree):
        if type(node) not in NODES:return False,f'node not permitted: {type(node).__name__}'
        if isinstance(node,ast.Name) and (node.id.startswith('__') or node.id in FORBIDDEN_NAMES):
            return False,f'name not permitted: {node.id}'
        if isinstance(node,ast.Name) and isinstance(node.ctx,ast.Load) and node.id not in bound:
            return False,f'unbound or builtin name not permitted: {node.id}'
        if isinstance(node,(ast.FunctionDef,ast.arg)):
            name=node.name if isinstance(node,ast.FunctionDef) else node.arg
            if name.startswith('__') or name in FORBIDDEN_NAMES:return False,f'name not permitted: {name}'
        if isinstance(node,ast.FunctionDef) and node.decorator_list:return False,'decorators not permitted'
        if isinstance(node,ast.Import):
            if any(alias.name not in MODULES or (alias.asname and alias.asname.startswith('__')) for alias in node.names):
                return False,'import not permitted'
        if isinstance(node,ast.ImportFrom):
            if node.level or node.module not in MODULES or any(a.name not in MODULE_ATTRS[node.module] for a in node.names):
                return False,'import not permitted'
        if isinstance(node,ast.Attribute):
            if node.attr.startswith('_'):return False,'private attribute not permitted'
            # Atributos de módulos matemáticos se autorizan solo con nombres
            # directamente importados; los métodos de datos están enumerados.
            imported={a.asname or a.name:a.name for n in ast.walk(tree) if isinstance(n,ast.Import) for a in n.names if a.name in MODULES}
            permitted_module=(isinstance(node.value,ast.Name) and node.value.id in imported
                              and node.attr in MODULE_ATTRS[imported[node.value.id]])
            if node.attr not in METHODS and not permitted_module:
                return False,f'attribute not permitted: {node.attr}'
    return True,'allowed'
