# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Do the renaming dance."""

import os

def rename(new, dst, logger=None):
    """Rename new to dst, logging messages to logger unless None.

    Return None if it worked, an os.error instance if not.

    """
    try:
        os.rename(new, dst)
    except os.error as err:
        if os.name == "posix":
            if logger is not None:
                logger.error("Can't rename %s to %s: %s", new, dst, err)
            return err
    else:
        if logger is not None:
            logger.debug("Renamed %s to %s", new, dst)
        return None
    # Windows fallback: move dst to dst.old if possible; otherwise remove dst
    old = dst + ".old"
    old_exists = os.path.exists(old)
    if old_exists:
        try:
            os.remove(old)
        except os.error as err:
            if logger is not None:
                logger.error("Can't remove %s: %s", old, err)
        else:
            old_exists = False
    if old_exists:
        try:
            os.remove(dst)
        except os.error as err:
            if logger is not None:
                logger.error("Can't remove %s: %s", dst, err)
            return err
    else:
        try:
            os.rename(dst, old)
        except os.error as err:
            if logger is not None:
                logger.error("Can't rename %s to %s: %s", dst, old, err)
            return err
    try:
        os.rename(new, dst)
    except os.error as err:
        if logger is not None:
            logger.error("Can't rename %s to %s: %s", new, dst, err)
        return err
    if logger is not None:
        logger.debug("Renamed %s to %s", new, dst)
    return None
