import os
from pathlib import Path

from dagster import Definitions, OpExecutionContext
from dagster_dbt import DbtCliResource, build_schedule_from_dbt_selection, dbt_assets

dbt_project_dir = Path(__file__).parent.joinpath({{ dbt_project_dir_relative_path_parts | join(', ')}})
dbt = DbtCliResource(project_dir=os.fspath(dbt_project_dir))

# If DAGSTER_DBT_PARSE_PROJECT_ON_LOAD is set, a manifest will be created at runtime.
# Otherwise, we expect a manifest to be present in the project's target directory.
if os.getenv("DAGSTER_DBT_PARSE_PROJECT_ON_LOAD"):
    dbt_parse_invocation = dbt.cli([{{ dbt_parse_command | join(', ')}}], manifest={})
    dbt_parse_invocation.wait()
    dbt_manifest_path = dbt_parse_invocation.target_path.joinpath("manifest.json")
else:
    dbt_manifest_path = dbt_project_dir.joinpath("target", "manifest.json")

@dbt_assets(manifest=dbt_manifest_path)
def {{ dbt_assets_name }}(context: OpExecutionContext, dbt: DbtCliResource):
    yield from dbt.cli(["build"], context=context).stream()


schedules = [
    build_schedule_from_dbt_selection(
        [{{ dbt_assets_name }}],
        job_name="materialize_dbt_models",
        cron_schedule="0 0 * * *",
        dbt_select="fqn:*",
    )
]

defs = Definitions(
    assets=[{{ dbt_assets_name }}],
    schedules=schedules,
    resources={
        "dbt": dbt,
    },
)
