from pathlib import Path
from typing import Literal, Tuple


def walk_size(paths: list[Path]) -> int:
    """Sum sizes of all regular files under the given paths, dedup by inode."""
    total = 0
    seen: set[int] = set()
    for root in paths:
        items = root.rglob("*") if root.is_dir() else [root]
        for p in items:
            try:
                if p.is_file():
                    st = p.stat()
                    if st.st_ino not in seen:
                        seen.add(st.st_ino)
                        total += st.st_size
            except OSError:
                pass
    return total


def find_root(
    path: Path, target_type: Literal["node"] | Literal["python"] | None
) -> Tuple[Path, Literal["node"] | Literal["python"] | None]:
    proj_type = identify_path(path, target_type)

    while proj_type is None:
        if path.parent != path:
            path = path.parent
            proj_type = identify_path(path, target_type)
        else:
            break

    return (path, proj_type)


def identify_path(
    path: Path, target_type: Literal["node"] | Literal["python"] | None
) -> Literal["node"] | Literal["python"] | None:
    if (target_type is None or target_type == "python") and (
        (path / "pyproject.toml").exists()
        or (path / "setup.cfg").exists()
        or (path / "requirements.txt").exists()
    ):
        return "python"
    elif (target_type is None or target_type == "node") and (
        path / "package-lock.json"
    ).exists():
        return "node"
    else:
        return None
