"""K8: a snapshot of the access policy of every route, derived from the real application (url_map) and the AST of its view functions.

The snapshot records, per route, the evidence of the policy that is IMPLEMENTED today: decorators, literal access levels that are compared
with ``access_level``, and calls of guard helpers. It does not define a new policy - it freezes the current one, so any change (new
route, removed route, changed decorator/level/guard, changed blueprint gate) fails the test until the change is reviewed and the
snapshot is updated on purpose (ARCH_WRITE_ROUTE_POLICY=1).
"""
import ast
import functools
import hashlib
import inspect
import re
import textwrap

GUARD_CALL = re.compile(r'(master|admin|require|forbid|allowed|permission|ownership|owner|scope|csrf|protect|guard|can_|denied|visible|is_.*(?:master|admin|unlocked))', re.I)
IGNORED_METHODS = {'HEAD', 'OPTIONS'}


def _dotted(node):
    if isinstance(node, ast.Call):
        return _dotted(node.func)
    if isinstance(node, ast.Attribute):
        base = _dotted(node.value)
        return (base + '.' if base else '') + node.attr
    if isinstance(node, ast.Name):
        return node.id
    return ''


def _function_ast(view):
    target = inspect.unwrap(view)
    try:
        source = textwrap.dedent(inspect.getsource(target))
    except (OSError, TypeError):
        return None
    for node in ast.parse(source).body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            return node
    return None


def _mentions_access_level(node):
    for sub in ast.walk(node):
        if isinstance(sub, ast.Constant) and sub.value == 'access_level':
            return True
        if isinstance(sub, ast.Name) and 'access_level' in sub.id:
            return True
        if isinstance(sub, ast.Attribute) and 'access_level' in sub.attr:
            return True
    return False


def _strings_in(node):
    return {sub.value for sub in ast.walk(node) if isinstance(sub, ast.Constant) and isinstance(sub.value, str)}


_SESSION = re.compile(r'\bsession\b')


def _uses_session(function, scope, depth=2, seen=None):
    """True when the view, or a helper it calls (same module, up to `depth` levels), reads the Flask session."""
    seen = seen if seen is not None else set()
    func = _function_ast(function)
    if func is None:
        return False
    if any(isinstance(n, ast.Name) and n.id == 'session' for n in ast.walk(func)):
        return True
    if depth:
        for node in ast.walk(func):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id not in seen:
                helper = scope.get(node.func.id)
                if callable(helper) and getattr(helper, '__module__', None) == getattr(function, '__module__', None):
                    seen.add(node.func.id)
                    if _uses_session(helper, scope, depth - 1, seen):
                        return True
    return False


def view_evidence(view):
    func = _function_ast(view)
    if func is None:
        return {'decorators': ['<source unavailable>'], 'levels': [], 'guards': [], 'session': False}
    decorators = sorted(d for d in (_dotted(x) for x in func.decorator_list) if d and not d.endswith('.route'))
    levels, guards = set(), set()
    scope = getattr(inspect.unwrap(view), '__globals__', {})
    for node in ast.walk(func):
        if isinstance(node, ast.Compare) and _mentions_access_level(node):
            levels |= _strings_in(node)
        elif isinstance(node, ast.Call):
            name = _dotted(node.func).rsplit('.', 1)[-1]
            if name and GUARD_CALL.search(name):
                helper = scope.get(name)
                guards.add('%s#%s' % (name, _hash(helper)) if callable(helper) else name)   # the helper's own code is part of the policy
    return {'decorators': decorators, 'levels': sorted(levels), 'guards': sorted(guards),
            'session': _uses_session(inspect.unwrap(view), scope)}     # evidence of per-user scoping/attribution (not proof of enforcement)


def _plain(function):
    while isinstance(function, functools.partial):
        function = function.func
    return function


def _hash(function):
    func = _function_ast(_plain(function))
    return hashlib.sha256(ast.dump(func).encode('utf-8')).hexdigest()[:16] if func is not None else 'unavailable'


def _hook_id(function):
    plain = _plain(function)
    name = getattr(plain, '__qualname__', None) or getattr(plain, '__name__', None) or type(plain).__name__
    return '%s.%s#%s' % (getattr(plain, '__module__', '?'), name, _hash(function))


def snapshot(app):
    """{'routes': {'METHODS /url': {...}}, 'gates': {...}} for the given Flask app."""
    routes = {}
    for rule in sorted(app.url_map.iter_rules(), key=lambda r: (r.rule, sorted(r.methods or ()))):
        if rule.endpoint == 'static' or rule.endpoint.endswith('.static'):
            continue
        methods = ','.join(sorted(set(rule.methods or ()) - IGNORED_METHODS))
        view = app.view_functions[rule.endpoint]
        entry = {'endpoint': rule.endpoint}
        entry.update(view_evidence(view))
        routes['%s %s' % (methods, rule.rule)] = entry
    gates = {}
    for scope, funcs in sorted(app.before_request_funcs.items(), key=lambda x: str(x[0])):
        gates['before_request:%s' % (scope or 'app')] = sorted(_hook_id(f) for f in funcs)
    for scope, funcs in sorted(app.after_request_funcs.items(), key=lambda x: str(x[0])):
        gates['after_request:%s' % (scope or 'app')] = sorted(_hook_id(f) for f in funcs)
    return {'routes': routes, 'gates': gates}


def compare(current, stored):
    """Human-readable differences between two snapshots (empty list = identical)."""
    problems = []
    cur, old = current['routes'], stored.get('routes', {})
    for key in sorted(set(cur) - set(old)):
        problems.append('NEW route (declare its policy by updating the snapshot): %s -> %s' % (key, cur[key]))
    for key in sorted(set(old) - set(cur)):
        problems.append('REMOVED route: %s' % key)
    for key in sorted(set(cur) & set(old)):
        if cur[key] != old[key]:
            problems.append('POLICY CHANGED %s: was %s, now %s' % (key, old[key], cur[key]))
    for key in sorted(set(current['gates']) | set(stored.get('gates', {}))):
        if current['gates'].get(key) != stored.get('gates', {}).get(key):
            problems.append('GATE CHANGED %s: was %s, now %s' % (key, stored.get('gates', {}).get(key), current['gates'].get(key)))
    return problems
