"""The Alexandria engine — the automation scripts that used to render into the vault
(Agent/scripts/**), now app-side (docs/DEVAULT.md step 1). Every runnable module is a
`--vault`-aware entrypoint:

    python -m alexandria_vault.engine.digest    --vault /path/to/vault --dry-run
    python -m alexandria_vault.engine.sweep     --vault /path/to/vault --plan
    python -m alexandria_vault.engine.digest_now --vault /path/to/vault ...

Two shared seams live here (and nothing else — no engine imports, so there are no
import cycles):

- `consume_vault_arg()` — the `--vault` mechanism. Every engine module freezes its
  vault/config at import time off the `VAULT_DIR` env var (the pre-existing override
  every locator honors), so the flag is consumed from argv into `VAULT_DIR` *before*
  the module-level locator runs. Runnables call this at the top of the module.
- `load_fresh(name)` — the package equivalent of the old sibling
  `spec_from_file_location` loads: import + reload, so module-level state frozen from
  the environment (DIGEST_TODAY, VAULT_DIR, CONFIG) is re-read on every load. The
  sweep/digest_now re-load digest.py *after* pinning DIGEST_TODAY and depend on that
  re-execution.
"""
import importlib
import os
import sys
from pathlib import Path


def resolve_vault() -> Path:
    """The engine's one vault resolution, replacing the drifted per-script
    locators (docs/DEVAULT.md step 2): ``vault_core.locate_vault`` — explicit
    ``$VAULT_DIR`` (validated), else a walk up from cwd — with a lenient cwd
    fallback. Lenient because engine modules freeze their vault at import time
    and must stay importable with no vault present (tests, library imports);
    a runnable that truly needs a vault fails at its first real read instead.
    """
    from alexandria_vault.vault_core import VaultNotFoundError, locate_vault
    try:
        return locate_vault()
    except VaultNotFoundError:
        return Path.cwd()


def consume_vault_arg(argv=None):
    """Pop `--vault PATH` (or `--vault=PATH`) out of argv into the VAULT_DIR env var.

    Called at the top of every runnable engine module, before its import-time vault
    locator. Consuming the flag (rather than teaching 15 argparse/`in sys.argv`
    parsers about it) keeps every existing flag parser working unchanged, and the env
    var propagates to every engine module the entrypoint goes on to import or
    `load_fresh`. An explicit flag wins over an inherited VAULT_DIR.
    """
    argv = sys.argv if argv is None else argv
    for i, a in enumerate(argv):
        if a == "--vault":
            if i + 1 >= len(argv):
                sys.exit("--vault requires a path")
            os.environ["VAULT_DIR"] = argv[i + 1]
            del argv[i:i + 2]
            return
        if a.startswith("--vault="):
            os.environ["VAULT_DIR"] = a.split("=", 1)[1]
            del argv[i]
            return


def load_fresh(name):
    """Import `alexandria_vault.engine.<name>` re-executed from scratch.

    The engine modules deliberately freeze env-derived state (VAULT_DIR, CONFIG,
    DIGEST_TODAY) at import; callers that change that state re-load their dependency
    to re-freeze it. The old file-location loads gave a fresh module object per call;
    reload re-executes the same module object in place, which every current caller
    uses sequentially.
    """
    return importlib.reload(importlib.import_module(f"alexandria_vault.engine.{name}"))
