import sqlglot
from sqlglot import exp

ALLOWED = {"customer", "orders", "lineitem", "nation", "region", "part", "partsupp", "supplier"}
FORBIDDEN = (exp.Insert, exp.Update, exp.Delete, exp.Drop, exp.Create, exp.Alter,
             exp.Command, exp.Merge)

def guard(sql: str, dialect: str = "duckdb", max_rows: int = 1000) -> str:
    stmts = [s for s in sqlglot.parse(sql, read=dialect) if s is not None]
    if len(stmts) != 1:
        raise ValueError("Exactly one statement allowed")
    root = stmts[0]
    if not isinstance(root, (exp.Select, exp.Union)):
        raise ValueError("Only SELECT queries allowed")
    if any(True for _ in root.find_all(*FORBIDDEN)):
        raise ValueError("Write/DDL detected")
    ctes = {c.alias_or_name.lower() for c in root.find_all(exp.CTE)}
    tables = {t.name.lower() for t in root.find_all(exp.Table)} - ctes
    if any(not t for t in tables) or not tables <= ALLOWED:
        raise ValueError(f"Table or table function not allowed: {sorted(tables - ALLOWED)}")
    if isinstance(root, exp.Select) and not root.args.get("limit"):
        root = root.limit(max_rows)
    return root.sql(dialect=dialect)