from datastar import *

TEST_PROJECT_NAME = "Example project for work_with_macros"
TEST_MACRO_NAME = "My new macro"

project = Project.create(TEST_PROJECT_NAME, "Created by datastar macro example script")

# Add a macro to project
macro = project.add_macro(TEST_MACRO_NAME)

# Add a macro (name is automatic)
macro = project.add_macro()
print(macro.name)

# Change macro details
macro.name = "a new name"
macro.description = "a new description"

# Persist macro details to db
macro.save()


# Get list of tasks in a macro
task_list = macro.get_tasks()
assert len(task_list) == 1
assert task_list[0] == "Start"  # Automatic start task only!

# Use a helper to add a task to a macro (for more on tasks see work_with_tasks.py)
sql_task = macro.add_run_sql_task(
    query=f"delete from some_table where city = 'london'",
    connection=project.get_sandbox(),
)

task_list = macro.get_tasks()
assert len(task_list) == 2

# Get an existing task by name
task_ref = macro.get_task(task_list[1])
assert task_ref
print(task_ref.name)

# Delete an existing task by name
macro.delete_task(task_ref.name)

# Delete a macro directly
macro2 = project.add_macro("Temp macro to delete")
macro2.delete()

# Start a macro run
run_id = macro.run()

# Wait for the macro run to complete
macro.wait_for_done(run_id, verbose=True)

# Clean up
project.delete()

print("Done")
