# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_pfmt.ipynb.

# %% auto 0
__all__ = ['fmtbyte', 'fmtpath']

# %% ../nbs/04_pfmt.ipynb 5
import os
from pathlib import Path
from typing import (Any, Union, Generator, Optional, TypeAlias, Callable, Iterable)

# %% ../nbs/04_pfmt.ipynb 7
from nchr import SPACE, TreeChr
from quac import (richtree, intq, strq, boolq)
from nlit.byte import (BYTE_SYMBS as UNITS, BYTE, BYTES)

# %% ../nbs/04_pfmt.ipynb 9
#| export


# %% ../nbs/04_pfmt.ipynb 11
PathFormatFunc: TypeAlias = Callable[[os.PathLike, strq, strq, strq], str]

# %% ../nbs/04_pfmt.ipynb 14
def _getidx(size: int = 1, base: int = 1000, units: Iterable = UNITS) -> int:
    for idx in range(len(units)):
        if size < base ** (idx + 1): return idx
    return idx

def _getexp(size: int = 1, base: int = 1000, units: Iterable = UNITS):
    idx = _getidx(size, base, units)
    return base ** (idx + 1)

def _getsuf(size: int = 1, base: int = 1000, units: Iterable = UNITS):
    idx = _getidx(size, base, units)
    return units[idx]

def _getnum(size: int = 1, base: int = 1000, precision: Optional[int] = 1, units: Iterable = UNITS):
    expo = _getexp(size, base, units)
    numb = float(base * size / expo)
    prec = precision or len(str(numb))
    return round(numb, prec)


# %% ../nbs/04_pfmt.ipynb 16
def fmtbyte(
    size: int = 1, 
    base: int = 1000, 
    sep: strq = SPACE, 
    precision: intq = 1, 
    units: Iterable = UNITS
):
    sfix = _getsuf(size, base, units)
    numb = _getnum(size, base, precision, units)
    if size == 1: return f'{size} {BYTE}'
    elif size < base: return f'{size:,} {BYTES}'
    return f'{numb:,.{precision}f}{sep}{sfix}'

# %% ../nbs/04_pfmt.ipynb 19
def _format_base_path(
    path: Path, 
    prefix: str = '', 
    treestr: TreeChr = TreeChr.TEE, 
    suffix: str = '',
    link: boolq = False, 
    size: boolq = False,
) -> str:
    pstr = prefix
    tstr = treestr or TreeChr.TEE
    lstr = ' file://' if link else ''
    nstr = path.name
    sstr = suffix
    bstr = f' ({fmtbyte(path.stat().st_size)})' if size else ''
    return f'{pstr}{tstr}{lstr}{nstr}{bstr}{sstr}'

def _format_rich_path(path: Path) -> Optional[richtree]:
    from rich.text import Text
    text = Text(path.name)
    size = fmtbyte(path.stat().st_size)
    text.stylize(f'link file://{path}')
    text.append(f' ({size})', 'cyan')
    return text

# %% ../nbs/04_pfmt.ipynb 21
def fmtpath(
    path: Path, 
    prefix: str = '',
    treestr: Optional[TreeChr] = None,
    suffix: str = '', 
    link: boolq = False, 
    size: boolq = False
) -> Union[richtree, str]:
    try: return _format_rich_path(path)
    except: return _format_base_path(path, prefix, treestr, suffix, link, size)
