#!/usr/bin/env nu
# Local build test for ontoref-daemon.
# Reads build_directives.ncl for IMAGE_BASE / RUST_VERSION, assembles the
# build context via rsync, and invokes docker build with --build-context stratumiops.
#
# Usage:
#   nu lian-build/ctx-test.nu                             # prepare ctx only
#   nu lian-build/ctx-test.nu --stage builder             # build builder stage
#   nu lian-build/ctx-test.nu --run                       # build final image
#
# Local lamina layers (after running lamina ctx-test.nu --layer rust/nickel):
#   nu lian-build/ctx-test.nu --run --image-base lamina --rust-version local
#
# ARG overrides (bypass NCL):
#   nu lian-build/ctx-test.nu --run --rust-version 1.90

def read_build_args [script_dir: string] {
    let directives = ($script_dir | path join "build_directives.ncl")

    if not ($directives | path exists) {
        print $"warning: ($directives) not found — using flag defaults"
        return {}
    }

    if (which nickel | is-empty) {
        print "warning: nickel not in PATH — using flag defaults"
        return {}
    }

    let lian_root = if "LIAN_BUILD_ROOT" in $env {
        $env.LIAN_BUILD_ROOT
    } else {
        $script_dir | path join ".." ".." "lian-build" | path expand
    }

    if not ($lian_root | path exists) {
        print $"warning: lian-build root not found at ($lian_root) — set LIAN_BUILD_ROOT"
        return {}
    }

    let result = do { ^nickel export --import-path $lian_root $directives } | complete
    if $result.exit_code != 0 {
        print $"warning: nickel eval failed — ($result.stderr)"
        return {}
    }
    $result.stdout | from json | get artifacts.0.build_args
}

def resolve [flag: string, ncl: record, key: string, fallback: string] {
    if not ($flag | is-empty) { $flag }
    else { $ncl | get -i $key | default $fallback }
}

def main [
    --stage: string    = ""
    --run
    --keep
    --platform: string = "linux/arm64"
    --rust-version: string = ""
    --image-base: string   = ""
] {
    let script_dir       = $env.FILE_PWD
    let project_root     = ($script_dir | path join "..") | path expand
    let stratumiops_root = ($project_root | path join ".." "stratumiops") | path expand

    if not ($stratumiops_root | path exists) {
        error make { msg: $"stratumiops not found at ($stratumiops_root)" }
    }

    let ncl          = read_build_args $script_dir
    let rust_version = resolve $rust_version $ncl "RUST_VERSION" "1.89"
    let image_base   = resolve $image_base   $ncl "IMAGE_BASE"   "reg.librecloud.online/lamina"

    let ctx = (^mktemp -d | str trim)

    print $"ctx:          ($ctx)"
    print $"project:      ($project_root)"
    print $"stratumiops:  ($stratumiops_root)"
    print $"IMAGE_BASE:   ($image_base)"
    print $"RUST_VERSION: ($rust_version)"

    ^rsync -a --delete ...[
        "--exclude=.git/"
        "--exclude=target/"
        "--exclude=.coder/"
        "--exclude=logs/"
        "--exclude=logs-archive/"
        "--exclude=lian-build/ctx-*"
        $"($project_root)/"
        $"($ctx)/"
    ]

    print $"context ready: ($ctx)"

    let dockerfile = ($project_root | path join "Dockerfile")

    let build_args = [
        "--build-arg"     $"RUST_VERSION=($rust_version)"
        "--build-arg"     $"IMAGE_BASE=($image_base)"
        "--build-context" $"stratumiops=($stratumiops_root)"
    ]

    if $run {
        let tag = "ontoref-daemon:local-test"
        print $"\nbuilding final image: ($tag)"
        ^docker build ...([
            "--platform" $platform
            "-t"         $tag
            "-f"         $dockerfile
        ] ++ $build_args ++ [$ctx])
        if not $keep { ^rm -rf $ctx }
        print "\nsmoke test"
        ^docker run --rm -p "7891:7891" $tag
        return
    }

    if ($stage | is-empty) {
        print $"\nctx ready at: ($ctx)"
        print "pass --stage <name> to build a specific stage, or --run for the final image"
        if not $keep { ^rm -rf $ctx }
        return
    }

    print $"\nbuilding stage: ($stage)"
    ^docker build ...([
        "--platform" $platform
        "--target"   $stage
        "-t"         $"ontoref-($stage):test"
        "-f"         $dockerfile
    ] ++ $build_args ++ [$ctx])

    if $keep { print $"ctx preserved: ($ctx)" } else { ^rm -rf $ctx }
    print $"\nimage: ontoref-($stage):test"
}
