label = "OnCall.AllTests"

load('ext://uibutton', 'cmd_button', 'location', 'text_input', 'bool_input')

e2e_tests_cmd=os.getenv("E2E_TESTS_CMD", "cd ../../grafana-plugin && pnpm test:e2e")
is_ci=config.tilt_subcommand == "ci"

local_resource(
    "e2e-tests",
    labels=[label],
    cmd=e2e_tests_cmd,
    trigger_mode=TRIGGER_MODE_MANUAL,
    auto_init=is_ci,
    resource_deps=["build-ui", "grafana", "grafana-oncall-app-provisioning-configmap", "engine", "celery", "build-oncall-plugin-backend"]
)

cmd_button(
    name="E2E Tests - headless run",
    argv=["sh", "-c", "pnpm --dir ./grafana-plugin test:e2e $STOP_ON_FIRST_FAILURE $TESTS_FILTER"],
    text="Restart headless run",
    resource="e2e-tests",
    icon_name="replay",
    inputs=[
        text_input("BROWSERS", "Browsers (e.g. \"chromium,firefox,webkit\")", "chromium", "chromium,firefox,webkit"),
        text_input("TESTS_FILTER", "Test filter (e.g. \"timezones.test quality.test\")", "", "Test file names to run"), 
        bool_input("STOP_ON_FIRST_FAILURE", "Stop on first failure", True, "-x", ""),
    ]
)

cmd_button(
    name="E2E Tests - open watch mode",
    argv=["sh", "-c", "pnpm --dir grafana-plugin test:e2e:watch"],
    text="Open watch mode",
    resource="e2e-tests",
    icon_name="visibility",
)

cmd_button(
    name="E2E Tests - show report",
    argv=["sh", "-c", "pnpm --dir grafana-plugin playwright show-report"],
    text="Show last HTML report",
    resource="e2e-tests",
    icon_name="assignment",
)

cmd_button(
    name="E2E Tests - stop current run",
    argv=["sh", "-c", "kill -9 $(pgrep -f test:e2e)"],
    text="Stop",
    resource="e2e-tests",
    icon_name="dangerous",
)

# Inspired by https://github.com/grafana/slo/blob/main/Tiltfile#L72
pod_engine_pytest_script = '''
set -eu
# get engine k8s pod name from tilt resource name
POD_NAME="$(tilt get kubernetesdiscovery "engine" -ojsonpath='{.status.pods[0].name}')"
kubectl exec "$POD_NAME" -- pytest . $STOP_ON_FIRST_FAILURE $TESTS_FILTER
'''
local_resource(
    "pytest-tests",
    labels=[label],
    cmd=['sh', '-c', pod_engine_pytest_script],
    trigger_mode=TRIGGER_MODE_MANUAL,
    auto_init=False,
    resource_deps=["engine"]
)

cmd_button(
    name="pytest Tests - headless run",
    argv=['sh', '-c', pod_engine_pytest_script],
    text="Run pytest",
    resource="pytest-tests",
    icon_name="replay",
    inputs=[
        text_input("TESTS_FILTER", "pytest optional arguments (e.g. \"apps/webhooks/tests/test_webhook.py::test_build_url_private_raises\")", "", "Test file names to run"), 
        bool_input("STOP_ON_FIRST_FAILURE", "Stop on first failure", True, "-x", ""),
    ]
)