import pathlib

import aiviro
from aiviro.modules.config import YAMLConfig


class RunEditorScenario(aiviro.BaseScenario):
    """Runs a scenario exported from the Aiviro Editor.

    The Editor exports each flow as a standalone Python module that defines a
    ``main(robot, input_variables)`` entry-point. :meth:`~.BaseScenario._run_app_script`
    loads that module dynamically and calls its ``main`` function, so the exported
    script runs inside a regular Core scenario together with its logging, metrics,
    reporting and error handling.
    """

    #: folder with the scripts exported from the Editor
    EXPORTED_SCRIPTS = pathlib.Path(__file__).parent / "exported"

    def __init__(self, config: YAMLConfig):
        super().__init__(config)
        # the robot name is defined in the .yaml config file
        self.r = self.robot(robot_name="web_robot")

    def _before_run(self) -> None:
        self.r.wait_until_ready()

    def _run(self) -> None:
        # ``input_variables`` are forwarded to the exported script's ``main`` function,
        # where they are exposed as the flow's input variables
        self._run_app_script(
            self.EXPORTED_SCRIPTS / "login_flow.py",
            robot=self.r,
            input_variables={"username": "aiviro", "password": "secret"},
        )


if __name__ == "__main__":
    # using the context manager closes the scenario automatically on exit
    main_config = YAMLConfig("main_config.yaml")
    with RunEditorScenario(main_config) as scenario:
        scenario.start()
