#!/usr/bin/env python3
import sys, os
from pathlib import Path

# Returns a parent path with pack.toml, or None if it can't be found
def search_recursive(dir: str | os.PathLike) -> Path | None:
    dir = Path(dir)
    pack = dir / "pack.toml"

    if pack.is_file():
        return dir

    # If we've made it to / without finding it, return None
    if dir.samefile("/"):
        return None

    # Otherwise, recurse
    return search_recursive(dir / "..")

def search(dir: str | os.PathLike) -> Path:
    new_dir = search_recursive(dir)
    if new_dir is not None:
        return new_dir
    else:
        return Path(dir)

def main():
    args = ["packwiz"] + sys.argv[1:]
    os.chdir(search("."))
    os.execvp("packwiz", args)


if __name__ == "__main__":
    main()