# Sync assets from the constellation parent (../assets/) into code/assets/.
# Canonical source: ../assets/  →  materialized copy: code/assets/  (tracked in git)
[doc("Sync assets from constellation parent ../assets/ into code/assets/")]
sync-assets:
    #!/usr/bin/env nu
    let src = (($env.PWD | path dirname) | path join "assets")
    let dst = ($env.PWD | path join "assets")

    if not ($src | path exists) {
        error make { msg: $"sync-assets: source not found: ($src)" }
    }

    def needs-copy [s: string, d: string]: nothing -> bool {
        if not ($d | path exists) { return true }
        (open --raw $s | hash sha256) != (open --raw $d | hash sha256)
    }

    def sync-file [s: string, d: string, label: string]: nothing -> record {
        if (needs-copy $s $d) {
            mkdir ($d | path dirname)
            cp $s $d
            { file: $label, action: "copied", sha256: (open --raw $d | hash sha256) }
        } else {
            { file: $label, action: "unchanged", sha256: (open --raw $d | hash sha256) }
        }
    }

    mut results = []

    # ── Logos for README.md ───────────────────────────────────────────────────
    for f in ["rustelo_dev-logo-h.svg", "rustelo_dev-logo-b-h.svg", "rustelo_dev-logo-b-v.svg", "rustelo_dev-logo-v.svg", "rustelo-imag.svg", "github-img.png"] {
        let s = ($src | path join "logos" $f)
        if ($s | path exists) {
            $results = ($results | append (sync-file $s ($dst | path join "logos" $f) $"logos/($f)"))
        }
    }

    let digest_input = ($results | each { |r| $"($r.file):($r.sha256)" } | sort | str join "\n")
    let aggregate = $"sha256:($digest_input | hash sha256)"
    let synced_at = (date now | format date "%Y-%m-%dT%H:%M:%SZ")

    {
        source: ($src | into string),
        aggregate_digest: $aggregate,
        synced_at: $synced_at,
        files: $results,
    } | to json | save --force ($dst | path join ".sync-manifest.json")

    let copied = ($results | where action == "copied" | length)
    let unchanged = ($results | where action == "unchanged" | length)
    print $"✓ sync-assets  copied=($copied) unchanged=($unchanged)  ($dst)"
