"""Static facts about the application code used by the architecture contracts. No imports of application modules.

Everything works on the AST of tracked non-test ``*.py`` files, so a scan never executes application code and never
needs configuration. Dynamic imports/SQL built at runtime are invisible by design (documented in docs/CONTRACTS.md).
"""
import ast
from functools import lru_cache
import re
import sys
from pathlib import Path

REPO = Path(__file__).resolve().parents[2]
PROJECT_ROOTS = ('InvestmentManager', 'InvestmentWebsite', 'modules', 'integrations', 'blueprints', 'tools', 'env_loader',
                 'flask_app', 'passenger_wsgi', 'run_local')


def module_name(path):
    name = path[:-3].replace('/', '.')
    return name[:-9] if name.endswith('.__init__') else name


@lru_cache(maxsize=1)
def files():
    """Application Python files (repo-relative, forward slashes): the package roots plus the root entry files; no tests/caches.

    A plain directory walk (no ``git`` subprocess: the test safety layer forbids launching processes).
    """
    found = []
    for root in PROJECT_ROOTS:
        entry = REPO / (root + '.py')
        if entry.is_file():
            found.append(root + '.py')
        base = REPO / root
        if base.is_dir():
            for path in base.rglob('*.py'):
                relative = path.relative_to(REPO)
                if '__pycache__' in relative.parts or 'node_modules' in relative.parts:
                    continue
                found.append(relative.as_posix())
    return tuple(sorted(set(found)))


@lru_cache(maxsize=1)
def modules():
    return {module_name(f): f for f in files()}


@lru_cache(maxsize=None)
def source(path):
    # utf-8-sig: 7 application files start with a BOM; a plain utf-8 read makes ast.parse fail on U+FEFF.
    return (REPO / path).read_text(encoding='utf-8-sig', errors='ignore')


@lru_cache(maxsize=None)
def tree(path):
    """AST of an application file. A file that cannot be parsed is an error: a contract must never silently skip code."""
    try:
        return ast.parse(source(path), filename=path)
    except SyntaxError as exc:
        raise AssertionError(f'architecture scan cannot parse {path}: {exc}') from exc


def package_of(path):
    name = module_name(path)
    return name if path.endswith('__init__.py') else (name.rsplit('.', 1)[0] if '.' in name else '')


def resolve(target):
    """Longest known project module that is a prefix of the dotted target (or None)."""
    known = modules()
    parts = target.split('.')
    for i in range(len(parts), 0, -1):
        candidate = '.'.join(parts[:i])
        if candidate in known:
            return candidate
    return None


@lru_cache(maxsize=None)
def imports(path):
    """((resolved_module, imported_name_or_None, lineno, is_lazy), ...) for every project import (lazy = inside a function)."""
    result = []
    module_level = {id(n) for n in tree(path).body}
    pkg = package_of(path)
    for node in ast.walk(tree(path)):
        lazy = id(node) not in module_level
        if isinstance(node, ast.Import):
            for alias in node.names:
                hit = resolve(alias.name)
                if hit:
                    result.append((hit, None, node.lineno, lazy))
        elif isinstance(node, ast.ImportFrom):
            if node.level:
                base = pkg.split('.') if pkg else []
                base = base[:len(base) - (node.level - 1)] if node.level > 1 else base
                mod = '.'.join(base + ([node.module] if node.module else []))
            else:
                mod = node.module or ''
            hit = resolve(mod) if mod else None
            for alias in node.names:
                sub = resolve(mod + '.' + alias.name) if mod else None
                if sub and sub != hit and sub.count('.') > (hit or '').count('.'):
                    result.append((sub, None, node.lineno, lazy))          # `from pkg import submodule`
                elif hit:
                    result.append((hit, alias.name, node.lineno, lazy))   # `from module import name`
    return tuple(result)


def import_edges():
    """{(src_module, dst_module)} over every file (a module is never its own target)."""
    edges = set()
    for module, path in modules().items():
        for dst, _name, _line, _lazy in imports(path):
            if dst != module:
                edges.add((module, dst))
    return edges


def area(module):
    """Coarse area used for cycle detection: first two path segments of the application packages."""
    parts = module.split('.')
    if parts[0] in ('InvestmentManager', 'InvestmentWebsite', 'modules', 'integrations') and len(parts) > 1:
        return '.'.join(parts[:2])
    return parts[0]


def alias_modules():
    """Compatibility aliases: ``sys.modules[__name__] = import_module(<canonical>)``. {alias_module: canonical_or_None}."""
    found = {}
    for module, path in modules().items():
        text = source(path)
        if 'sys.modules[__name__]' not in text:
            continue
        match = re.search(r"sys\.modules\[__name__\]\s*=\s*import_module\(\s*['\"]([\w.]+)['\"]", text)
        found[module] = match.group(1) if match else None
    return found


def strongly_connected(edges):
    """Non-trivial strongly connected components of a directed graph given as {(a, b)}."""
    graph = {}
    for a, b in edges:
        graph.setdefault(a, set()).add(b)
        graph.setdefault(b, set())
    index, low, stack, on, out, counter = {}, {}, [], set(), [], [0]

    def visit(v):
        index[v] = low[v] = counter[0]
        counter[0] += 1
        stack.append(v)
        on.add(v)
        for w in sorted(graph[v]):
            if w not in index:
                visit(w)
                low[v] = min(low[v], low[w])
            elif w in on:
                low[v] = min(low[v], index[w])
        if low[v] == index[v]:
            comp = []
            while True:
                w = stack.pop()
                on.discard(w)
                comp.append(w)
                if w == v:
                    break
            if len(comp) > 1:
                out.append(sorted(comp))

    sys.setrecursionlimit(max(sys.getrecursionlimit(), 10000))
    for v in sorted(graph):
        if v not in index:
            visit(v)
    return out


_DML = re.compile(r"""(?:INSERT\s+(?:OR\s+\w+\s+)?INTO|REPLACE\s+INTO|DELETE\s+FROM|\bUPDATE(?!\s+OF\b))\s+["`\[]?([A-Za-z_]\w*)""", re.I)
_NOT_TABLES = {'set', 'select', 'where', 'or', 'sqlite_sequence', 'before', 'after', 'of', 'on', 'from', 'the', 'a'}
# Throw-away probe table created by the hosting preflight in a private temporary database (not application data).
SCRATCH_TABLES = {'t'}


def sql_writes(path):
    """{table (lower-case): count} of DML write statements in string literals (literal parts of f-strings included).

    ``UPDATE x`` only counts when the same literal also has ``SET`` (so prose such as "Update the cache" is not a write).
    Statements whose table name is computed at runtime (``INTO {name}``) are invisible: documented limitation.
    """
    counts = {}
    for node in ast.walk(tree(path)):
        parts = []
        if isinstance(node, ast.Constant) and isinstance(node.value, str):
            parts = [node.value]
        elif isinstance(node, ast.JoinedStr):
            parts = [''.join(v.value for v in node.values if isinstance(v, ast.Constant) and isinstance(v.value, str))]
        for text in parts:
            if len(text) < 14:
                continue
            for match in _DML.finditer(text):
                table = match.group(1).lower()
                head = match.group(0).lstrip().upper()
                if table in _NOT_TABLES or table in SCRATCH_TABLES:
                    continue
                if head.startswith('UPDATE') and not re.search(r'\bSET\b', text[match.end():], re.I):
                    continue
                counts[table] = counts.get(table, 0) + 1
    return counts


def sql_calls(path):
    """Number of direct SQL executions / sqlite3 connections in a file."""
    n = 0
    for node in ast.walk(tree(path)):
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            if node.func.attr in ('execute', 'executemany', 'executescript'):
                n += 1
            elif node.func.attr == 'connect' and isinstance(node.func.value, ast.Name) and node.func.value.id == 'sqlite3':
                n += 1
    return n


def env_accesses(path):
    """Number of reads of the process environment (os.environ / os.getenv / `from os import environ`)."""
    n = 0
    for node in ast.walk(tree(path)):
        if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'os' and node.attr in ('environ', 'getenv', 'putenv'):
            n += 1
        elif isinstance(node, ast.ImportFrom) and node.module == 'os' and any(a.name in ('environ', 'getenv') for a in node.names):
            n += 1
    return n


def private_accesses(path):
    """Uses of ``_name`` attributes/imports of OTHER project modules: ``mod._x`` and ``from mod import _x``."""
    n = 0
    aliases = set()
    for node in ast.walk(tree(path)):
        if isinstance(node, ast.ImportFrom):
            mod = node.module or ''
            projectish = bool(node.level) or mod.split('.')[0] in PROJECT_ROOTS
            for alias in node.names:
                if projectish:
                    aliases.add(alias.asname or alias.name)
                    if alias.name.startswith('_') and not alias.name.startswith('__') and mod:
                        n += 1
        elif isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name.split('.')[0] in PROJECT_ROOTS:
                    aliases.add(alias.asname or alias.name.split('.')[0])
    for node in ast.walk(tree(path)):
        if (isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in aliases
                and node.attr.startswith('_') and not node.attr.startswith('__')):
            n += 1
    return n


def third_party_imports(path):
    """Top-level package names of every import (stdlib and third party), for purity checks."""
    names = set()
    for node in ast.walk(tree(path)):
        if isinstance(node, ast.Import):
            names.update(a.name.split('.')[0] for a in node.names)
        elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
            names.add(node.module.split('.')[0])
    return names
