"""File and path snippets built on pathlib."""
import hashlib
import json
import os
import tempfile
from pathlib import Path


def read_lines(path):
    """Lines of a text file without trailing newlines.

    >>> p = Path(tempfile.mkdtemp()) / 'a.txt'; _ = p.write_text('x\\ny\\n')
    >>> read_lines(p)
    ['x', 'y']
    """
    return Path(path).read_text(encoding='utf-8').splitlines()


def write_atomic(path, text):
    """Write a file so readers never see a half-written version.

    Writes to a temp file in the same folder, then os.replace()s it.

    >>> p = Path(tempfile.mkdtemp()) / 'cfg.json'
    >>> write_atomic(p, '{}'); p.read_text()
    '{}'
    """
    path = Path(path)
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f'.{path.name}.')
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
    except BaseException:
        os.unlink(tmp)
        raise


def load_json(path, default=None):
    """Read JSON, returning ``default`` if the file does not exist.

    >>> load_json('/no/such/file.json', default={})
    {}
    """
    try:
        return json.loads(Path(path).read_text(encoding='utf-8'))
    except FileNotFoundError:
        return default


def sha256_file(path, chunk_size=1 << 20):
    """SHA-256 of a file, read in chunks so big files are fine.

    >>> p = Path(tempfile.mkdtemp()) / 'b.bin'; _ = p.write_bytes(b'abc')
    >>> sha256_file(p)[:16]
    'ba7816bf8f01cfea'
    """
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while block := f.read(chunk_size):
            h.update(block)
    return h.hexdigest()


def find_files(root, pattern='*', exclude_dirs=('.git', 'node_modules', '__pycache__', '.venv')):
    """Recursively list files matching a glob, skipping noisy folders.

    >>> d = Path(tempfile.mkdtemp()); (d / 'node_modules').mkdir(); _ = (d / 'node_modules' / 'x.py').write_text('')
    >>> _ = (d / 'app.py').write_text(''); [p.name for p in find_files(d, '*.py')]
    ['app.py']
    """
    root = Path(root)
    return sorted(p for p in root.rglob(pattern)
                  if p.is_file() and not set(p.relative_to(root).parts[:-1]) & set(exclude_dirs))


def dir_size(path):
    """Total size in bytes of every file under ``path``.

    >>> d = Path(tempfile.mkdtemp()); _ = (d / 'a').write_bytes(b'12345')
    >>> dir_size(d)
    5
    """
    return sum(p.stat().st_size for p in Path(path).rglob('*') if p.is_file())


def ensure_dir(path):
    """Create a folder (and parents) if missing; return it as a Path.

    >>> d = ensure_dir(Path(tempfile.mkdtemp()) / 'a' / 'b'); d.is_dir()
    True
    """
    path = Path(path)
    path.mkdir(parents=True, exist_ok=True)
    return path
