"""S3: no NEW dynamic SQL in the user-facing layers (and the shared L0 query modules, since S4.2) without a review.

K4 (tests/architecture) counts SQL calls in the web layer; it does not look at HOW the statement is built. This guard fails when a route /
public-site module executes a statement that is not a plain literal (f-string with values, concatenation, %, .format, or a variable) unless
the function is listed below with the reason it is safe. Reviewed in the S3 audit: identifiers only ever come from constants, a fixed
whitelist, the SQLite schema (`sqlite_master` / `PRAGMA table_info`) or are quoted after such a check; every value is a bound parameter.
"""
import ast
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SCOPE = ['InvestmentManager/routes', 'InvestmentManager/middleware', 'InvestmentWebsite', 'blueprints', 'modules/core']

REVIEWED = {
    ('InvestmentManager/routes/dbshell.py', '_dbshell_table_columns'): 'table name verified in sqlite_master first, then quoted (master + DB Shell unlock)',
    ('InvestmentManager/routes/dbshell.py', 'dbshell_find_duplicates'): 'identifiers verified against PRAGMA table_info and quoted (master + unlock)',
    ('InvestmentManager/routes/dbshell.py', 'dbshell_replace_text'): 'table/column verified against the schema and quoted; values bound (master + unlock)',
    ('InvestmentManager/routes/dbshell.py', 'dbshell_table_data'): 'table verified in sqlite_master and quoted; LIMIT bound (master + unlock)',
    ('InvestmentManager/routes/dbshell.py', 'dbshell_update_cell'): 'table/column verified against the schema and quoted; value bound (master + unlock)',
    ('InvestmentManager/routes/offer_catalog.py', 'add_offer'): 'column lists are code constants; values bound',
    ('InvestmentManager/routes/offer_catalog.py', 'update_offer'): 'column names filtered through PRAGMA table_info of the real tables; values bound',
    ('modules/core/offer_queries.py', 'list_offer_rows_by_ids'): 'IN (?, ?, ...) placeholders only, ids cast to int (moved from routes/crm_clients.py, S4.2)',
    ('modules/core/offer_queries.py', 'search_offer_rows'): 'WHERE built from constant fragments with ?; LIKE values bound (moved from routes/crm_clients.py, S4.2)',
    ('InvestmentWebsite/services/catalog.py', 'get_active_agents'): 'IN placeholders built from ids read from the database',
    ('InvestmentWebsite/services/catalog.py', 'get_estates_catalog'): 'where/join from build_catalog_query_parts (constants + ?), order by from a whitelist map',
    ('InvestmentWebsite/services/catalog.py', 'get_normalized_filter_options'): 'table asserted, column is a code constant from investment_facade',
}


def _dynamic_sites():
    sites = set()
    for scope in SCOPE:
        for path in sorted((ROOT / scope).rglob('*.py')):
            if '__pycache__' in path.parts:
                continue
            tree = ast.parse(path.read_text(encoding='utf-8-sig'))
            parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}
            for node in ast.walk(tree):
                if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in {'execute', 'executemany', 'executescript'} and node.args):
                    continue
                first = node.args[0]
                is_literal = isinstance(first, ast.Constant) and isinstance(first.value, str)
                is_plain_fstring = isinstance(first, ast.JoinedStr) and not any(isinstance(v, ast.FormattedValue) for v in first.values)
                if is_literal or is_plain_fstring:
                    continue
                owner = node
                while owner in parents:
                    owner = parents[owner]
                    if isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)):
                        break
                name = owner.name if isinstance(owner, (ast.FunctionDef, ast.AsyncFunctionDef)) else '<module>'
                sites.add((path.relative_to(ROOT).as_posix(), name))
    return sites


def test_every_dynamic_sql_site_in_the_user_facing_layers_has_been_reviewed():
    found = _dynamic_sites()
    unreviewed = sorted(found - set(REVIEWED))
    assert not unreviewed, (
        'New non-literal SQL in a route / public-site module. Make identifiers come from a whitelist or the schema, bind every value, '
        f'then add the function to REVIEWED with the reason: {unreviewed}')


def test_the_review_list_has_no_stale_entries():
    stale = sorted(set(REVIEWED) - _dynamic_sites())
    assert not stale, f'REVIEWED lists functions that no longer build dynamic SQL (remove them): {stale}'
