"""Where the working files of The Unfolding Map find the seated corpora and each other.

Every script in this tree that reads a corpus or another folder takes the path from here, so the tree
runs wherever it is put: in the Alexanarch repository (rebuild/unfolding-map/), or as published at
revelationfirst.com/unfolding/notebook/work/ beside a clone of the Alexanarch repository.

    UM        this folder, the root of the working tree
    CORPORA   the seated corpora (Alexanarch data/corpora)
    REVFIRST  the unfoldings of revelationfirst.com (its unfolding folder), read by sources/m2.py and sources/inventory.py

Each of the last two can be set by environment variable: ALEXANARCH_CORPORA, REVFIRST_UNFOLDING.
Otherwise the first that exists is taken, going up from this folder: data/corpora in an enclosing
folder, then alexanarch/data/corpora beside one (a clone of the repository next to this one).
A name is resolved only when a script imports it, so a script that needs only CORPORA runs without REVFIRST.
"""
import os, pathlib

UM = pathlib.Path(__file__).resolve().parent


def _find(env, *rels):
    if os.environ.get(env):
        return str(pathlib.Path(os.environ[env]))
    for p in UM.parents:
        for r in rels:
            if (p / r).is_dir():
                return str(p / r)
    raise SystemExit(f"paths.py: cannot find {rels[0]}; set {env} to its folder")


def __getattr__(name):
    if name == "CORPORA":
        return _find("ALEXANARCH_CORPORA", "data/corpora", "alexanarch/data/corpora")
    if name == "REVFIRST":
        return _find("REVFIRST_UNFOLDING", "unfolding", "revelationfirst-com/unfolding")
    raise AttributeError(name)
