"""Offline FTS5 query-language fixture. Python 3.9+, SQLite with FTS5.
Run without arguments for the demonstration; --test for regression tests.
Uses an in-memory database only. No network or model calls.
"""
import sqlite3
import sys
import unittest


SQL = "SELECT rowid FROM docs WHERE docs MATCH ? ORDER BY rowid"


def phrase(text):
    """Encode one FTS5 token phrase, not a byte-exact substring."""
    if not isinstance(text, str) or not text.strip() or len(text) > 1024:
        raise ValueError("expected nonblank text, at most 1024 code points")
    if any(ord(c) < 32 or ord(c) == 127 or 0xD800 <= ord(c) <= 0xDFFF for c in text):
        raise ValueError("control characters and surrogate code points refused")
    return '"' + text.replace('"', '""') + '"'


def database():
    con = sqlite3.connect(":memory:")
    try:
        con.execute("CREATE VIRTUAL TABLE docs USING fts5(body, tokenize='unicode61')")
        con.executemany("INSERT INTO docs(rowid, body) VALUES (?, ?)", [
            (1, "rollback guide"),
            (2, "payroll guide"),
            (3, "rollback OR payroll"),
            (4, 'the operator said "rollback"'),
            (5, "release-check procedure"),
            (6, "body payroll reference"),
            (7, "rolling deployment"),
            (8, "café handbook"),
        ])
    except Exception:
        con.close()
        raise
    return con


def raw_query(con, query):
    """Intentionally exposes the FTS query language, despite SQL binding."""
    return [row[0] for row in con.execute(SQL, (query,))]


def literal_phrase(con, text):
    return raw_query(con, phrase(text))


class Tests(unittest.TestCase):
    def setUp(self):
        self.con = database()
        self.addCleanup(self.con.close)

    def test_boolean_operator(self):
        self.assertEqual(raw_query(self.con, "rollback OR payroll"), [1, 2, 3, 4, 6])
        self.assertEqual(literal_phrase(self.con, "rollback OR payroll"), [3])

    def test_unclosed_quote(self):
        with self.assertRaises(sqlite3.OperationalError):
            raw_query(self.con, '"rollback')
        self.assertEqual(literal_phrase(self.con, '"rollback'), [1, 3, 4])

    def test_embedded_quotes(self):
        self.assertEqual(phrase('said "rollback"'), '"said ""rollback"""')
        self.assertEqual(literal_phrase(self.con, 'said "rollback"'), [4])

    def test_column_syntax_is_text(self):
        self.assertEqual(raw_query(self.con, "body:payroll"), [2, 3, 6])
        self.assertEqual(literal_phrase(self.con, "body:payroll"), [6])

    def test_prefix_syntax_is_text(self):
        self.assertEqual(raw_query(self.con, "roll*"), [1, 3, 4, 7])
        self.assertEqual(literal_phrase(self.con, "roll*"), [])

    def test_token_phrase_not_exact_bytes(self):
        self.assertEqual(literal_phrase(self.con, "release check"), [5])
        self.assertEqual(literal_phrase(self.con, "CAFE"), [8])

    def test_order_and_adjacency(self):
        self.assertEqual(literal_phrase(self.con, "guide rollback"), [])
        self.assertEqual(literal_phrase(self.con, "rollback payroll"), [])
        self.assertEqual(literal_phrase(self.con, "rollback guide"), [1])

    def test_punctuation_only(self):
        self.assertEqual(literal_phrase(self.con, "***"), [])

    def test_invalid_input(self):
        for value in [None, True, 42, "", "  ", "x" * 1025, "x\x00y", "x\ny", "\ud800"]:
            with self.subTest(value=repr(value)), self.assertRaises(ValueError):
                literal_phrase(self.con, value)
        self.assertEqual(literal_phrase(self.con, "x" * 1024), [])

    def test_quoted_operator_cannot_break_out(self):
        self.assertEqual(literal_phrase(self.con, 'rollback" OR "payroll'), [3])
        self.assertEqual(literal_phrase(self.con, "'; DROP TABLE docs; --"), [])
        self.assertEqual(self.con.execute("SELECT count(*) FROM docs").fetchone()[0], 8)


if __name__ == "__main__":
    if sys.argv[1:] == ["--test"]:
        unittest.main(argv=[sys.argv[0]], verbosity=2)
    elif sys.argv[1:]:
        raise SystemExit("usage: python3 rag-fts-query-boundary.py [--test]")
    else:
        connection = database()
        try:
            query = "rollback OR payroll"
            print("SQL-bound raw FTS:", raw_query(connection, query))
            print("SQL-bound token phrase:", literal_phrase(connection, query))
            print("SQLite:", sqlite3.sqlite_version)
        finally:
            connection.close()
