# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_copy.ipynb.

# %% auto 0
__all__ = ['safecopy']

# %% ../nbs/02_copy.ipynb 4
import copy
from atyp import AnyQ, StrQ, BoolQ
from ispec.utils import arg1st

# %% ../nbs/02_copy.ipynb 5
from .cons import SCOPY, DCOPY

# %% ../nbs/02_copy.ipynb 7
def safecopy(
    *args, 
    attr: StrQ = 'copy', 
    useattr: BoolQ = True, 
    usecopy: BoolQ = True, 
    shallow: BoolQ = True,
    deep: BoolQ = False
) -> AnyQ:
    '''Copies the first non-None argument, or returns the last argument if all are None.'''
    copyable = arg1st(*args)

    if attr in SCOPY | DCOPY:        
        attr = SCOPY.canon if attr in SCOPY else DCOPY.canon

    if shallow and attr != SCOPY.canon and not hasattr(copyable, SCOPY.canon):
        attr = SCOPY.canon

    if deep    and attr != DCOPY.canon and not hasattr(copyable, DCOPY.canon):
        attr = DCOPY.canon

    if hasattr(copyable, attr) and useattr:
        return getattr(copyable, attr)()
    elif usecopy and deep:
        return copy.deepcopy(copyable)
    elif usecopy:
        return copy.copy(copyable)
    return None
