# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/60_pttn.ipynb.

# %% auto 0
__all__ = ['stemnums', 'pathpttns']

# %% ../nbs/60_pttn.ipynb 5
import re
from pathlib import Path

# %% ../nbs/60_pttn.ipynb 7
from quac import (callq)
from nchr import U1
from chck import iscall, isnone, notnone, isdig
from asto import cast, asnum
# from pttn import getpttn

# %% ../nbs/60_pttn.ipynb 9
from .util import relparts, aspath

# %% ../nbs/60_pttn.ipynb 11
def _getgroup(s: str, pttn: re.Pattern = None, group: int = 1, flags: re.RegexFlag = re.NOFLAG):
    return res.group(group) if (res := re.search(pttn, s, flags)) else None

def _getpttn(s: str,  pttn: re.Pattern = None, group: int = 1, dtype: type = None):
    return cast(asnum(val), dtype, retnone=False) if notnone(val := _getgroup(s, pttn, group)) else None

# %% ../nbs/60_pttn.ipynb 13
def stemnums(path: Path) -> list[int]:
    '''Extract the underscore separated numeric values from the stem of a path.'''
    stem = (path := aspath(path)).name
    nums = list(map(int, filter(isdig, stem.split(U1))))
    return nums

# %% ../nbs/60_pttn.ipynb 15
def pathpttns(
    dirpath: Path, 
    relpath: Path = None,
    pttn_dict: dict = None,
    prep_path: callq = None,
    anti_pttn: re.compile = None,
    exclude: set = {},
) -> dict:
    pres = dict(path = dirpath)
    path = prep_path(dirpath) if iscall(prep_path) else dirpath
    
    if pttn_dict is None: return {}

    for part in relparts(path, relpath, exclude):
        isanti = notnone(anti_pttn) and isnone(re.search(anti_pttn, part))
        for name, pttn in pttn_dict.items():
            if notnone(val := _getpttn(part, pttn)) and not isanti:
                pres.setdefault(name, val)
    return pres
