import os

from backend.utils.logging_utils import get_logger

logger = get_logger(__name__)


def backup_sqlite_db(db_path):
    """
    Creates a backup of a SQLite database, correctly handling WAL mode.
    Returns the path to the backup file, or None if the backup failed.
    """
    import datetime

    from backend.sqlite_compat import sqlite3

    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    backup_path = f"{db_path}.{timestamp}.bak"

    logger.info(f"Backing up {db_path} to {backup_path}...")

    try:
        source_conn = sqlite3.connect(db_path)
        backup_conn = sqlite3.connect(backup_path)

        with backup_conn:
            source_conn.backup(backup_conn)

        logger.info(f"Backup successful.")
        return backup_path

    except sqlite3.Error as e:
        logger.exception(f"An error occurred during backup: {e}")
        # Clean up the possibly incomplete backup file
        if os.path.exists(backup_path):
            os.remove(backup_path)
        return None
    finally:
        if "source_conn" in locals() and source_conn:
            source_conn.close()
        if "backup_conn" in locals() and backup_conn:
            backup_conn.close()


def restore_sqlite_db(db_path, backup_path):
    """
    Restores a SQLite database from a backup file in a safe and robust way.

    This function first removes any existing database files (including -wal and -shm)
    to prevent conflicts, then copies the backup file to the original database path.

    Args:
        db_path (str): The path to the database file to restore.
        backup_path (str): The path to the backup file.

    Returns:
        bool: True if the restore was successful, False otherwise.
    """
    import os
    import shutil

    logger.info(f"Attempting to restore database '{db_path}' from backup '{backup_path}'")

    try:
        # 1. Verify that the backup file actually exists
        if not os.path.exists(backup_path):
            logger.info(f"Error: Backup file not found at '{backup_path}'")
            return False

        # 2. Safely remove any remnants of the old database
        for ext in ["", "-wal", "-shm"]:
            old_db_file = db_path + ext
            if os.path.exists(old_db_file):
                os.remove(old_db_file)
                logger.info(f"Removed old database file: {old_db_file}")

        # 3. Copy the backup file to the target path
        shutil.copy2(backup_path, db_path)
        logger.info(f"Successfully restored database to '{db_path}'")

        return True

    except Exception as e:
        logger.exception(f"A critical error occurred during database restoration: {e}")
        return False
