# Cherrypy-foundation.
# Copyright (C) 2026 IKUS Software
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import re


def _regexp_replace(value, pattern, replacement):
    if value is None:
        return None
    return re.sub(pattern, replacement, value)


def _reverse(string):
    if string is None:
        return None
    return string[::-1]


def _split_part(string, delimiter, position):
    if string is None:
        return None
    parts = string.split(delimiter)
    return parts[position - 1] if 0 < position <= len(parts) else None


def register_all_functions(connection):
    """
    Register all missing PostgreSQL-compatible functions into a SQLite engine.
    Call this once after creating your SQLAlchemy engine.
    """
    connection.create_function("regexp_replace", 3, _regexp_replace, deterministic=True)
    connection.create_function("reverse", 1, _reverse, deterministic=True)
    connection.create_function("split_part", 3, _split_part, deterministic=True)
