"""
GLAMWalk -- Volume 3: Data at Scale
12_multi_institution_orchestrator.py

Running every institution's import script in one sequenced process with isolated per-institution failure handling and --only filtering -- the fix for both 'did I run all of them' and a real database write-lock collision.

Source: Volume Three, Section 11.2 -- One Orchestrator, Sequenced, With Isolated Failure
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import argparse
import traceback


def _make_stub_importer(name):
    """Stand-in for a real institution import function — see
    Volume Three, Chapters 2-7 for the real NGA/Cooper Hewitt/
    Cleveland/Walters/Tate/Rijksmuseum importers this would call."""
    def _importer(commit=False):
        print(f"(pretending to import {name}, commit={commit})")
    return _importer


import_nga = _make_stub_importer("nga")
import_cooper_hewitt = _make_stub_importer("cooper_hewitt")
import_cleveland = _make_stub_importer("cleveland")
import_walters = _make_stub_importer("walters")
import_tate = _make_stub_importer("tate")
import_rijksmuseum = _make_stub_importer("rijksmuseum")

INSTITUTION_IMPORTERS = {
    "nga": import_nga,
    "cooper_hewitt": import_cooper_hewitt,
    "cleveland": import_cleveland,
    "walters": import_walters,
    "tate": import_tate,
    "rijksmuseum": import_rijksmuseum,
}

def run_all(commit=False, only=None):
    targets = only or list(INSTITUTION_IMPORTERS.keys())

    for name in targets:
        importer = INSTITUTION_IMPORTERS.get(name)
        if not importer:
            print(f"Unknown institution: {name}, skipping.")
            continue

        print(f"\n=== {name} ===")
        try:
            importer(commit=commit)
        except Exception as e:
            # ONE institution's failure must never take down the whole
            # run — log it clearly and move on to the next institution.
            print(f"FAILED: {name}: {e}")
            traceback.print_exc()
            continue

    print("\nAll institutions processed.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--commit", action="store_true")
    parser.add_argument("--only", type=str, help="Comma-separated list, e.g. nga,tate")
    args = parser.parse_args()

    only = args.only.split(",") if args.only else None
    run_all(commit=args.commit, only=only)
