use ../../workspace/notation.nu [get-workspace-path]
use ../../utils/nickel_processor.nu [ncl-eval]

# Resolve the provisioning root directory for --import-path.
def dag-provisioning-root [] : nothing -> string {
    $env.PROVISIONING? | default "/usr/local/provisioning"
}

# Export a Nickel file and parse as JSON, returning Err on non-zero exit.
def dag-nickel-export [path: string] : nothing -> record {
    let prov = (dag-provisioning-root)
    ncl-eval $path [$prov]
}

# Load the DAG execution config for a workspace.
#
# Resolution order:
#   1. `provisioning/schemas/config/dag/main.ncl` — base defaults (execution, resolution, events)
#   2. `{workspace_root}/infra/{infra}/dag.ncl`   — workspace composition; top-level keys override defaults
#
# The workspace dag.ncl is a WorkspaceComposition — it is intentionally included here so that
# workspace-level overrides to execution/resolution/events blocks (if present) propagate.
# If the workspace dag.ncl has no such keys, the merge is a no-op for those fields.
#
# Returns a record with at minimum: execution, resolution, events.
export def get-dag-config [
    workspace?: string  # Workspace name; if omitted uses PROVISIONING root defaults only
    --infra (-i): string = "wuji"  # Infra sub-directory name
] : nothing -> record {
    let prov = (dag-provisioning-root)
    let defaults_path = ($prov | path join "schemas" "config" "dag" "main.ncl")

    if not ($defaults_path | path exists) {
        error make { msg: $"dag config: defaults not found at ($defaults_path)" }
    }

    let defaults = (dag-nickel-export $defaults_path)

    if ($workspace == null) or ($workspace | is-empty) {
        return $defaults
    }

    let ws_root = (get-workspace-path $workspace)
    if ($ws_root | is-empty) {
        error make { msg: $"dag config: workspace '($workspace)' not found in registry" }
    }

    let dag_path = ($ws_root | path join "infra" $infra "dag.ncl")
    if not ($dag_path | path exists) {
        return $defaults
    }

    let ws_dag = (dag-nickel-export $dag_path)

    # Shallow merge: workspace keys (execution, resolution, events) overwrite defaults at top level.
    # Nu 0.110.0+ has no 'merge deep'; top-level block override is the correct granularity here.
    $defaults | merge $ws_dag
}
