import subprocess

from textual.app import App

from juist.justfiles.models import JuistConfig
from juist.tui.screens.recipe_selection import RecipeSelectionScreen, Selection


class Juist(App[Selection | None]):
    def __init__(self, config: JuistConfig) -> None:
        super().__init__()
        self._config = config

    def on_mount(self) -> None:
        self.push_screen(RecipeSelectionScreen(self._config), self.exit)


def run_tui(config: JuistConfig) -> None:
    selection = Juist(config).run()
    if selection is not None:
        subprocess.run(  # noqa: S603
            ["just", "--justfile", str(selection.source.path), selection.recipe.name, *selection.args.values()],  # noqa: S607
            check=False,
        )
