"""BBEye script runner — invoked via: python3 -m bbeye script.py"""

import sys
import importlib.util

from bbeye import run


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 -m bbeye <script.py>", file=sys.stderr)
        return 1

    script_path = sys.argv[1]
    spec = importlib.util.spec_from_file_location("_user_script", script_path)
    if spec is None or spec.loader is None:
        print(f"Cannot load script: {script_path}", file=sys.stderr)
        return 1

    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    on_request = getattr(module, "onRequest", None)
    on_response = getattr(module, "onResponse", None)

    if not on_request and not on_response:
        print(f"Script must define onRequest and/or onResponse: {script_path}", file=sys.stderr)
        return 1

    run(on_request=on_request, on_response=on_response)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
