"""Recipe "find_vault": find a vault's GUID by its name, then work in that vault.

The program knows only the server and the user's credentials: it logs in at server level, lists
the vaults the user can access, picks the one with the given name and opens a session to it with
LogInWithSession, without authenticating again. MFILES_VAULT is not needed.

Usage: python recipes/find_vault.py [vault name]
Without a name it lists the vaults and opens the first one.
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from mfiles_client import MFilesClient, run  # noqa: E402
from recipe_helpers import CLIENT_NAME  # noqa: E402

from mfiles import IRPCVaults_pb2, IRPCVaults_pb2_grpc  # noqa: E402

# Logging in with the all-zero vault GUID opens a server-level session.
SERVER_LEVEL = "{00000000-0000-0000-0000-000000000000}"


def main() -> None:
    name = sys.argv[1] if len(sys.argv) > 1 else ""
    with MFilesClient.from_env(CLIENT_NAME, log_in=False) as client:
        # [START find-vault]
        client.config.vault = SERVER_LEVEL
        client.log_in()
        vaults = client.stub(IRPCVaults_pb2_grpc.IRPCVaultsStub).GetVaults(
            IRPCVaults_pb2.GetVaultsRequest(exclude_vaults_user_cannot_access=True)).vaults
        for vault in vaults:
            print(f"{vault.display_name}: {vault.guid}")
        matches = [v for v in vaults if not name or v.display_name.casefold() == name.casefold()]
        if not matches:
            raise SystemExit(f"No vault named '{name}' that this user can access")
        session = client.switch_to_vault(matches[0].guid)
        # [END find-vault]
        print(f"Logged in to {matches[0].display_name} ({client.config.vault}) as "
              f"{session.account_name}")

        client.log_out()
        print("Logged out")


if __name__ == "__main__":
    run(main)
