{% import "macros.jinja" as macros %}
from pathlib import Path
import os
{% if imports_slot -%}
{{ imports_slot }}
{%- endif -%}
from kptn.caching.submit import submit
{#- from kptn.deploy.storage_key import read_branch_storage_key #}
from kptn.runner import cli_parser, parse_and_validate_tasks
from kptn.util.pipeline_config import PipelineConfig
{#- from kptn.util.runtime_config import ensure_pythonpath #}

os.environ["KPTN_FLOW_TYPE"] = "vanilla"
os.environ.setdefault("KPTN_DB_TYPE", "sqlite")

VALID_TASKS: set[str] = { {% for name in task_names %}"{{ name }}"{% if not loop.last %}, {% endif %}{% endfor %} }

def {{pipeline_name}}(task_list: list[str] = [], ignore_cache: bool = False):
    pipeline_config = PipelineConfig(
        TASKS_CONFIG_PATH=str(Path(__file__).parent / "{{ rel_tasks_conf_path }}"),
        PIPELINE_NAME="{{pipeline_name}}",{% if r_tasks_dir %}
        R_TASKS_DIRS=(str(Path(__file__).parent / "{{ rel_r_tasks_dir }}"),),{% endif %}
    )

    task_list = parse_and_validate_tasks(task_list, VALID_TASKS)

    opts = (
        pipeline_config,
        set(task_list),
        ignore_cache,
    )
    {#- Gather rendered submit blocks so we can join them with a fixed separator -#}
    {%- set ns = namespace(submits=[]) -%}
    {%- for name in task_names -%}
        {%- set ns.submits = ns.submits + [macros.submit(name, deps_lookup[name], python_task_names, tasks_dict)] -%}
    {%- endfor -%}
{# Prefix and join submit calls with single newlines to avoid blank gaps #}
{{ '\n    ' ~ (ns.submits | join('\n    ')) }}


if __name__ == "__main__":
    args, _ = cli_parser().parse_known_args()

    {{pipeline_name}}(
        task_list=args.tasks or None,
        ignore_cache=args.force,
    )
