#!/usr/bin/env python3
"""Python 3.11+ / stdlib only. Run: python3 fde-query-boundaries.py compare.

All inputs and fictional rows are fixed. Deliberately unsafe queries are local,
isolated anti-examples. No files, network, credentials, or supplied SQL are used.
"""

import json
import sqlite3
import sys


ESCAPE_LIKE_INPUT = True  # Changed-copy experiment: False changes literal-like only.
FIXTURE = (
    ("north", "N-1", "Operator's guide"),
    ("north", "N-2", "Pump 100% checklist"),
    ("north", "N-3", "Shared handbook"),
    ("south", "S-1", "Shared handbook"),
    ("south", "S-2", "South pump notes"),
)
CASE_NAMES = ("quoted-title", "predicate-injection", "missing-scope", "wildcard-input")
SELECT = "SELECT workspace, id, title FROM documents"
SCOPED = SELECT + " WHERE workspace = :workspace AND title = :title ORDER BY workspace, id"
LIKE = SELECT + " WHERE workspace = :workspace AND title LIKE :pattern ESCAPE '\\' ORDER BY workspace, id"


def escape_like(value):
    """Escape the escape character first, then SQL LIKE's two wildcards."""
    return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")


def attempt(db, label, sql, parameters):
    result = {"label": label, "sql": sql, "parameters": parameters,
              "rows": [], "row_count": 0, "sql_error_type": None}
    try:
        # Sort actual rows in Python: the injected comment removes SQL ORDER BY.
        rows = sorted(db.execute(sql, parameters).fetchall())
        result["rows"] = [dict(zip(("workspace", "id", "title"), row)) for row in rows]
        result["row_count"] = len(rows)
    except sqlite3.Error as error:
        result["sql_error_type"] = type(error).__name__
    return result


def in_fixture(run, extra_rows=()):
    """A fresh :memory: connection, with read-only learner queries after setup."""
    db = sqlite3.connect(":memory:")
    cleanup = {"connection_closed": False, "verified_closed": False}
    try:
        db.execute("CREATE TABLE documents (workspace TEXT NOT NULL, id TEXT NOT NULL, "
                   "title TEXT NOT NULL, PRIMARY KEY (workspace, id))")
        db.executemany("INSERT INTO documents VALUES (?, ?, ?)", FIXTURE + extra_rows)
        db.commit()
        db.execute("PRAGMA query_only = ON")
        result = {"attempts": run(db), "cleanup": cleanup}
    finally:
        db.close()
        cleanup["connection_closed"] = True
        try:
            db.execute("SELECT 1")
        except sqlite3.ProgrammingError:
            cleanup["verified_closed"] = True
    return result


def run_case(name):
    value = {"quoted-title": "Operator's guide", "predicate-injection": "x' OR 1=1 --",
             "missing-scope": "Shared handbook", "wildcard-input": "%"}[name]

    def run(db):
        if name in ("quoted-title", "predicate-injection"):
            unsafe = SELECT + f" WHERE workspace = 'north' AND title = '{value}' ORDER BY workspace, id"
            return [attempt(db, "Deliberately unsafe: local isolated interpolation anti-example", unsafe, {}),
                    attempt(db, "Bound value with workspace scope", SCOPED,
                            {"workspace": "north", "title": value})]
        if name == "missing-scope":
            return [attempt(db, "Bound value; workspace predicate omitted",
                            SELECT + " WHERE title = :title ORDER BY workspace, id", {"title": value}),
                    attempt(db, "Bound value with workspace scope", SCOPED,
                            {"workspace": "north", "title": value})]
        literal = escape_like(value) if ESCAPE_LIKE_INPUT else value
        return [attempt(db, "Bound raw LIKE contains pattern with workspace scope", LIKE,
                        {"workspace": "north", "pattern": f"%{value}%"}),
                attempt(db, "Bound literal LIKE contains pattern with workspace scope", LIKE,
                        {"workspace": "north", "pattern": f"%{literal}%"})]

    return {"name": name, "input": value, **in_fixture(run)}


def report(names):
    cases = [run_case(name) for name in names]
    return {
        "scope": "Fixed fictional local SQLite query examples; no security audit, qualification, or database row-level security proof.",
        "runtime": {"python": sys.version.split()[0], "sqlite": sqlite3.sqlite_version},
        "fixture": {"database": ":memory:", "fresh_database_per_case": True,
                    "row_count": len(FIXTURE), "learner_queries_read_only": True},
        "cleanup": {"connections_opened": len(cases),
                    "connections_closed": sum(case["cleanup"]["connection_closed"] for case in cases),
                    "all_verified_closed": all(case["cleanup"]["verified_closed"] for case in cases)},
        "cases": cases,
    }


def parse_args(args):
    if not args or args == ["compare"]:
        return "compare", CASE_NAMES
    if args == ["--self-test"]:
        return "self-test", CASE_NAMES
    if len(args) == 2 and args[0] == "case" and args[1] in CASE_NAMES:
        return "case", (args[1],)
    raise ValueError("Use compare, case " + "|".join(CASE_NAMES) + ", or --self-test; no other inputs are accepted.")


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def self_test():
    output = report(CASE_NAMES)
    cases = output["cases"]
    expected = (([], ["N-1"]), (["N-1", "N-2", "N-3", "S-1", "S-2"], []),
                (["N-3", "S-1"], ["N-3"]), (["N-1", "N-2", "N-3"], ["N-2"]))
    for case, outcomes in zip(cases, expected):
        for index, (query, ids) in enumerate(zip(case["attempts"], outcomes)):
            require([row["id"] for row in query["rows"]] == ids, case["name"] + ": actual rows differ")
            require(query["row_count"] == len(ids), case["name"] + ": count differs")
            expected_error = "OperationalError" if case["name"] == "quoted-title" and index == 0 else None
            require(query["sql_error_type"] == expected_error, case["name"] + ": SQL error differs")
        require(case["cleanup"]["verified_closed"], case["name"] + ": connection still open")
    require(output["cleanup"]["connections_closed"] == 4, "All four case connections must close")
    require(cases[3]["attempts"][0]["parameters"]["pattern"] == "%%%", "Raw LIKE pattern differs")
    require(cases[3]["attempts"][1]["parameters"]["pattern"] == "%\\%%", "Literal LIKE pattern differs")

    # An independent fixture verifies actual underscore and backslash matching,
    # including a decoy which an unescaped underscore would also match.
    supplements = (("north", "U-1", "under_score"), ("north", "U-2", "underXscore"),
                   ("north", "B-1", "back\\slash"))
    probes = in_fixture(lambda db: [
        attempt(db, "Literal " + term, LIKE,
                {"workspace": "north", "pattern": "%" + escape_like(term) + "%"})
        for term in ("_", "\\")], supplements)
    require([[row["id"] for row in query["rows"]] for query in probes["attempts"]] == [["U-1"], ["B-1"]],
            "Literal underscore/backslash matching differs")
    require(probes["cleanup"]["verified_closed"], "Supplemental connection still open")
    require(parse_args([]) == parse_args(["compare"]), "Default must compare")
    for name in CASE_NAMES:
        require(parse_args(["case", name]) == ("case", (name,)), "Case selection differs")
    for invalid in (["unknown"], ["compare", "extra"], ["case"], ["case", "unknown"],
                    ["--self-test", "extra"], ["--sql", "SELECT 1"], ["--help"]):
        try:
            parse_args(invalid)
        except ValueError:
            continue
        raise AssertionError("Unknown arguments accepted")
    output["self_test"] = {"passed": True, "supplemental_literal_checks": probes,
                           "invalid_argument_checks": 7}
    output["cleanup"]["connections_opened"] += 1
    output["cleanup"]["connections_closed"] += 1
    return output


def main(args):
    try:
        mode, names = parse_args(args)
        if sys.version_info < (3, 11):
            raise ValueError("Python 3.11 or newer is required")
        output = self_test() if mode == "self-test" else report(names)
    except (ValueError, AssertionError) as error:
        print(json.dumps({"error_type": type(error).__name__, "error": str(error)}))
        return 2 if isinstance(error, ValueError) else 1
    print(json.dumps(output, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
