Private/Helpers.ps1

#Requires -Version 7.0
# ============================================================
# DrawManagement — Private Helpers
# Internal functions not exported to the user
#
# REVIEW CHANGES vs original:
# [HELP-01] ConvertTo-DrawStyle: added empty-hashtable guard and
# sorted key output so style strings are deterministic
# across PS versions (hashtable key order is not guaranteed).
# [HELP-02] Get-EscapedXml: switched from [string]::IsNullOrEmpty
# to [string]::IsNullOrWhiteSpace for consistency; added
# -LiteralPath on Test-Path calls throughout the module.
# [HELP-03] Read-VssxFile: added try/catch around per-master parsing
# so a single corrupt master does not abort the whole import;
# moved Add-Type inside the try block with -ErrorAction Stop
# to surface assembly-load failures clearly.
# [HELP-04] Read-VssxFile: removed ?? operator (PS 5.1 incompatible);
# replaced with explicit if/else.
# [HELP-05] Read-VssxFile: $zip.Dispose() in finally may throw if
# OpenRead itself threw — added null guard.
# [HELP-06] Read-ZipEntry: added try/finally to guarantee stream/reader
# disposal even when ReadToEnd throws.
# [HELP-07] Build-LegendPage: added guard for empty $Shapes array and
# for missing required keys (Name, Style) in each descriptor.
# [HELP-08] Resolve-CellId: tightened type check — [DrawEdge] is not
# a valid cell reference; now errors explicitly.
# [HELP-09] New-DrawGeometry: renamed internal helper to
# Format-DrawGeometry (Verb-Noun, New- implies side-effects).
# ============================================================

function ConvertTo-DrawStyle {
    <#
    .SYNOPSIS
        Builds a draw.io style string from a hashtable of properties.
    .DESCRIPTION
        Keys and values are joined as key=value pairs separated by
        semicolons. Output is deterministic — keys sorted alphabetically.
    .EXAMPLE
        ConvertTo-DrawStyle @{ rounded=1; fillColor='#dae8fc' }
        # Returns: "fillColor=#dae8fc;rounded=1;"
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)][hashtable]$Properties
    )

    # [HELP-01] guard and sort for determinism
    if ($Properties.Count -eq 0) { return '' }

    $parts = foreach ($k in ($Properties.Keys | Sort-Object)) {
        "$k=$($Properties[$k])"
    }
    return ($parts -join ';') + ';'
}

function Get-EscapedXml {
    <#
    .SYNOPSIS
        XML-escapes a string for safe embedding in attributes/text nodes.
    .DESCRIPTION
        Returns an empty string for null/whitespace input rather than
        throwing, so callers do not need defensive checks.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(ValueFromPipeline)][string]$Value
    )
    process {
        # [HELP-02] IsNullOrWhiteSpace catches tab/newline edge cases
        if ([string]::IsNullOrWhiteSpace($Value)) { return '' }
        return [System.Security.SecurityElement]::Escape($Value)
    }
}

function Format-DrawGeometry {
    <#
    .SYNOPSIS
        Returns an mxGeometry XML fragment string.
    .DESCRIPTION
        [HELP-09] Renamed from New-DrawGeometry — New- implies resource
        creation with side effects; Format- is correct for a pure
        string-building helper.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter()][double]$X      = 0,
        [Parameter()][double]$Y      = 0,
        [Parameter()][double]$Width  = 120,
        [Parameter()][double]$Height = 60,
        [Parameter()][switch]$Relative
    )
    if ($Relative) {
        return '<mxGeometry relative="1" as="geometry"/>'
    }
    return "<mxGeometry x=`"$X`" y=`"$Y`" width=`"$Width`" height=`"$Height`" as=`"geometry`"/>"
}

function Read-VssxFile {
    <#
    .SYNOPSIS
        Reads a .vssx/.vss file and returns a list of [DrawStencil] objects.
    .DESCRIPTION
        A .vssx file is a ZIP (OPC) archive. This function:
          1. Loads System.IO.Compression.FileSystem safely.
          2. Opens the ZIP and parses visio/masters/masters.xml.
          3. For each Master element reads the corresponding part file.
          4. Extracts shape name, dimensions (Visio inches × 96 dpi)
             and any ForeignData embedded image.
          5. Returns a [DrawStencil] per shape.

        [HELP-03] Per-master errors are caught and logged as warnings
        rather than aborting the whole import.
    #>

    [CmdletBinding()]
    [OutputType([DrawStencil[]])]
    param(
        [Parameter(Mandatory)][string]$Path
    )

    # [HELP-02] use -LiteralPath so square brackets in paths don't expand
    if (-not (Test-Path -LiteralPath $Path)) {
        throw "Read-VssxFile: file not found: '$Path'"
    }

    # [HELP-03] load assembly with explicit error handling
    try {
        Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop
    }
    catch {
        throw "Read-VssxFile: could not load System.IO.Compression.FileSystem. Error: $_"
    }

    $stencils = New-Object 'System.Collections.Generic.List[DrawStencil]'
    # [FIX-12] masters whose artwork is Visio geometry rather than an
    # embedded raster — counted so the caller can be told, not guessed at
    [int]$noArtwork = 0
    $zip      = $null

    try {
        $zip = [System.IO.Compression.ZipFile]::OpenRead($Path)

        # ── Relationship map ──────────────────────────────────────────
        $relMap    = @{}
        $relsEntry = $zip.Entries | Where-Object { $_.FullName -eq 'visio/masters/_rels/masters.xml.rels' }

        if ($relsEntry) {
            try {
                $relsXml = Read-ZipEntry -Entry $relsEntry
                $relsDoc = [xml]$relsXml
                foreach ($rel in $relsDoc.Relationships.Relationship) {
                    $relMap[$rel.Id] = $rel.Target
                }
            }
            catch {
                Write-Warning "Read-VssxFile: could not parse relationship file — $_. Part mapping may be incomplete."
            }
        }

        # ── Masters index ─────────────────────────────────────────────
        $mastersEntry = $zip.Entries | Where-Object { $_.FullName -eq 'visio/masters/masters.xml' }
        if (-not $mastersEntry) {
            Write-Warning "Read-VssxFile: 'visio/masters/masters.xml' not found — this may not be a valid VSSX file."
            return $stencils
        }

        $mastersXml = Read-ZipEntry -Entry $mastersEntry
        $mastersDoc = [xml]$mastersXml

        foreach ($master in @($mastersDoc.DocumentElement.ChildNodes)) {
            if ($master -isnot [System.Xml.XmlElement] -or $master.LocalName -ne 'Master') { continue }
            # [FIX-38] Every attribute read goes through Get-XmlAttr. VMware's
            # official vmw_Icons.vssx has masters without NameU; the bare
            # $master.NameU threw under StrictMode, and so did the same read
            # inside the catch block's warning — which escaped to the outer
            # handler and aborted the WHOLE import as "failed to parse".
            $mId = Get-XmlAttr -Node $master -Name 'ID'
            # [HELP-03] wrap each master in its own try so one bad shape
            # does not kill the entire import
            try {
                $mName = Get-XmlAttr -Node $master -Name 'NameU'
                if ([string]::IsNullOrWhiteSpace($mName)) { $mName = Get-XmlAttr -Node $master -Name 'Name' }
                if ([string]::IsNullOrWhiteSpace($mName)) {
                    Write-Verbose "Read-VssxFile: skipping master with no NameU or Name (ID=$mId)"
                    continue
                }

                # Resolve relationship ID → part filename
                $relNode = $master.ChildNodes | Where-Object {
                    $_ -is [System.Xml.XmlElement] -and $_.LocalName -eq 'Rel'
                } | Select-Object -First 1
                $relId = ''
                if ($null -ne $relNode) {
                    $relId = $relNode.GetAttribute(
                        'id',
                        'http://schemas.openxmlformats.org/officeDocument/2006/relationships')
                    if ([string]::IsNullOrWhiteSpace($relId)) {
                        $relId = Get-XmlAttr -Node $relNode -Name 'id'
                    }
                }

                # [HELP-04] PS 5.1-safe: no ?? operator
                $partTarget = if ([string]::IsNullOrWhiteSpace($relId)) { $null } else { $relMap[$relId] }
                if ([string]::IsNullOrWhiteSpace($partTarget)) {
                    $partTarget = "master$mId.xml"
                }

                $partTarget = $partTarget -replace '^\.\.\/', ''
                $partPath   = "visio/masters/$partTarget"

                $partEntry = $zip.Entries | Where-Object { $_.FullName -eq $partPath }
                if (-not $partEntry) {
                    Write-Warning "Read-VssxFile: part '$partPath' not found for master '$mName' — skipped."
                    continue
                }

                $partXml = Read-ZipEntry -Entry $partEntry
                $partDoc = [xml]$partXml

                # ── Dimensions (Visio inches × 96 dpi = pixels) ───────
                $wNode = $partDoc.SelectSingleNode("//*[local-name()='Cell'][@Name='Width']")
                $hNode = $partDoc.SelectSingleNode("//*[local-name()='Cell'][@Name='Height']")

                # [HELP-04] PS 5.1 safe — no ??
                $wRaw = if ($wNode) { Get-XmlAttr -Node $wNode -Name 'V' } else { $null }
                $hRaw = if ($hNode) { Get-XmlAttr -Node $hNode -Name 'V' } else { $null }

                $wIn = if (-not [string]::IsNullOrWhiteSpace($wRaw)) {
                    try { [double]$wRaw } catch { 1.0 }
                } else { 1.0 }

                $hIn = if (-not [string]::IsNullOrWhiteSpace($hRaw)) {
                    try { [double]$hRaw } catch { 1.0 }
                } else { 1.0 }

                $wPx = [int][Math]::Max([Math]::Round($wIn * 96), 16)
                $hPx = [int][Math]::Max([Math]::Round($hIn * 96), 16)

                $stencil         = [DrawStencil]::new($mName)
                $stencil.Width   = $wPx
                $stencil.Height  = $hPx

                # ── Embedded image (ForeignData) ───────────────────────
                $fdNode = $partDoc.SelectSingleNode("//*[local-name()='ForeignData']")
                if ($fdNode) {
                    $imgB64 = $fdNode.InnerText -replace '\s', ''
                    if (-not [string]::IsNullOrWhiteSpace($imgB64)) {
                        $stencil.ImageData   = "data:image/png;base64,$imgB64"
                        $stencil.AspectFixed = $true
                    }
                }

                # [FIX-12] Masters with no embedded raster carry their artwork
                # as Visio geometry, which this module does not translate.
                # The original code quietly substituted a plain rectangle, so
                # those shapes arrived looking like deliberate blank boxes.
                # Emit a visibly provisional chip instead and count them, so
                # the caller is told what was lost rather than discovering it
                # in the finished diagram.
                if ([string]::IsNullOrWhiteSpace($stencil.ImageData)) {
                    $stencil.Style = ('rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;' +
                                      'strokeColor=#b3b3b3;dashed=1;dashPattern=3 3;' +
                                      'fontColor=#666666;fontSize=10;fontStyle=2;')
                    $noArtwork++
                }

                $null = $stencils.Add($stencil)
            }
            catch {
                Write-Warning "Read-VssxFile: error processing master '$(Get-XmlAttr -Node $master -Name 'NameU')' (ID=$mId) — $_. Skipped."
            }
        }
    }
    catch {
        # Re-throw errors from ZIP open or masters.xml parse — these are fatal
        throw "Read-VssxFile: failed to parse '$Path'. Error: $_"
    }
    finally {
        # [HELP-05] null guard before Dispose
        if ($null -ne $zip) {
            try { $zip.Dispose() } catch { <# silently ignore dispose errors #> }
        }
    }

    # [FIX-12] Say plainly what could not be converted. Visio geometry is a
    # different model from mxGraph stencils and translating it is out of
    # scope — but silently shipping blank boxes is worse than saying so.
    if ($noArtwork -gt 0) {
        Write-Warning (
            "Read-VssxFile: $noArtwork of $($stencils.Count) shapes in " +
            "'$(Split-Path -Leaf $Path)' store their artwork as Visio geometry rather " +
            "than an embedded image. Those are imported as dashed placeholder chips — " +
            "the name and size are correct but the artwork is not. For a proper icon, " +
            "either re-export the stencil from Visio with embedded images, or use a " +
            "built-in draw.io shape (Find-DrawShape).")
    }

    Write-Verbose "Read-VssxFile: loaded $($stencils.Count) shapes from '$Path'"
    return $stencils
}

function Read-ZipEntry {
    <#
    .SYNOPSIS
        Reads a ZipArchiveEntry as a UTF-8 string.
    .DESCRIPTION
        [HELP-06] Both StreamReader and Stream are disposed in a
        finally block to guarantee cleanup even if ReadToEnd throws.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)][System.IO.Compression.ZipArchiveEntry]$Entry
    )

    $stream  = $null
    $reader  = $null
    $content = $null

    try {
        $stream  = $Entry.Open()
        $reader  = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::UTF8)
        $content = $reader.ReadToEnd()
    }
    catch {
        throw "Read-ZipEntry: failed to read '$($Entry.FullName)'. Error: $_"
    }
    finally {
        if ($null -ne $reader)  { try { $reader.Dispose()  } catch { } }
        if ($null -ne $stream)  { try { $stream.Dispose()  } catch { } }
    }

    return $content
}

function Build-LegendPage {
    <#
    .SYNOPSIS
        Generates a standardised Legend DrawPage from shape descriptors.
    .DESCRIPTION
        [HELP-07] Now validates that each shape descriptor contains at
        minimum a 'Name' and 'Style' key before building cells, and
        guards against an empty $Shapes array.
    .PARAMETER Shapes
        Array of hashtables. Required keys: Name, Style.
        Optional keys: UsedFor, FillColor.
    .PARAMETER PageName
        Name for the legend tab. Default: '📋 Legend'.
    #>

    [CmdletBinding()]
    [OutputType([DrawPage])]
    param(
        [Parameter(Mandatory)][hashtable[]]$Shapes,
        [Parameter()][string]$PageName = '📋 Legend'
    )

    # [HELP-07] guard
    if ($Shapes.Count -eq 0) {
        throw "Build-LegendPage: Shapes array must not be empty."
    }

    $page = [DrawPage]::new($PageName)

    # Title cell
    $title        = [DrawCell]::new('<b>Diagram Legend</b>')
    $title.Style  = 'text;html=1;fontSize=18;fontStyle=1;align=left;strokeColor=none;fillColor=none;'
    $title.X = 40; $title.Y = 20; $title.Width = 600; $title.Height = 32
    $page.AddCell($title)

    # Column headers
    $headers = @('Shape', 'Name', 'Used For', 'Style Key', 'Fill Colour')
    $hxPos   = @(40, 160, 320, 520, 840)
    $hWidths = @(110, 150, 190, 310, 100)
    for ($i = 0; $i -lt $headers.Count; $i++) {
        $hdr        = [DrawCell]::new($headers[$i])
        $hdr.Style  = 'text;html=1;fontSize=11;fontStyle=1;align=left;fillColor=#dae8fc;strokeColor=#6c8ebf;'
        $hdr.X      = $hxPos[$i]
        $hdr.Y      = 60
        $hdr.Width  = $hWidths[$i]
        $hdr.Height = 24
        $page.AddCell($hdr)
    }

    $row = 84
    foreach ($s in $Shapes) {
        # [HELP-07] validate required descriptor keys
        if (-not $s.ContainsKey('Name') -or [string]::IsNullOrWhiteSpace($s['Name'])) {
            Write-Warning "Build-LegendPage: shape descriptor missing 'Name' key — skipped."
            continue
        }
        if (-not $s.ContainsKey('Style') -or [string]::IsNullOrWhiteSpace($s['Style'])) {
            Write-Warning "Build-LegendPage: shape descriptor for '$($s['Name'])' missing 'Style' — skipped."
            continue
        }

        $shapeName  = $s['Name']
        $shapeStyle = $s['Style']
        $usedFor    = if ($s.ContainsKey('UsedFor')) { $s['UsedFor'] } else { '' }
        $fillColor  = if ($s.ContainsKey('FillColor') -and
                         -not [string]::IsNullOrWhiteSpace($s['FillColor'])) {
            $s['FillColor']
        } else { '#ffffff' }

        # Shape preview
        $preview        = [DrawCell]::new($shapeName)
        $preview.Style  = $shapeStyle
        $preview.X      = 40; $preview.Y = $row; $preview.Width = 110; $preview.Height = 28

        # A glyph (index stencil or icon) is fitted at its own proportions and
        # centred, without the name on top — stretched to 110x28 with a label
        # over it, an icon is unrecognisable. The name has its own column.
        $glyph = $null
        if ($shapeStyle -match '(?:^|;)shape=(mxgraph\.[A-Za-z0-9_.]+);') { $glyph = $Matches[1] }
        elseif ($shapeStyle -match 'image=img/lib/([^;]+);') { $glyph = $Matches[1] }
        if ($null -ne $glyph) {
            Initialize-DrawShapeIndex
            $entry = $script:DrawShapeFlat | Where-Object { $_.Name -eq $glyph } | Select-Object -First 1
            if ($null -ne $entry) {
                $k = [Math]::Min(26 / [Math]::Max(1, $entry.Height), 100 / [Math]::Max(1, $entry.Width))
                $preview.Width  = [Math]::Max(1, [Math]::Round($entry.Width * $k))
                $preview.Height = [Math]::Max(1, [Math]::Round($entry.Height * $k))
                $preview.X      = 40 + (110 - $preview.Width) / 2
                $preview.Y      = $row + (28 - $preview.Height) / 2
                $preview.Label  = ''
            }
        }
        $page.AddCell($preview)

        # Name label
        $nameCell        = [DrawCell]::new($shapeName)
        $nameCell.Style  = 'text;html=1;fontSize=11;align=left;strokeColor=none;fillColor=none;'
        $nameCell.X      = 160; $nameCell.Y = $row; $nameCell.Width = 150; $nameCell.Height = 28
        $page.AddCell($nameCell)

        # Used-for label
        $useCell        = [DrawCell]::new($usedFor)
        $useCell.Style  = 'text;html=1;fontSize=11;align=left;strokeColor=none;fillColor=none;'
        $useCell.X      = 320; $useCell.Y = $row; $useCell.Width = 190; $useCell.Height = 28
        $page.AddCell($useCell)

        # Style key (displayed as monospace text)
        $styleCell        = [DrawCell]::new($shapeStyle)
        $styleCell.Style  = 'text;html=1;fontSize=9;fontFamily=Courier New;align=left;strokeColor=none;fillColor=none;'
        $styleCell.X      = 520; $styleCell.Y = $row; $styleCell.Width = 310; $styleCell.Height = 28
        $page.AddCell($styleCell)

        # Fill colour swatch
        $swatchStyle        = "rounded=1;fillColor=$fillColor;strokeColor=#666666;fontSize=9;"
        $swatch             = [DrawCell]::new($fillColor)
        $swatch.Style       = $swatchStyle
        $swatch.X           = 840; $swatch.Y = $row; $swatch.Width = 100; $swatch.Height = 28
        $page.AddCell($swatch)

        $row += 32
    }

    return $page
}

function Get-XmlAttr {
    <#
    .SYNOPSIS
        Reads an XML attribute safely under Set-StrictMode -Version Latest.
    .DESCRIPTION
        [FIX-05] $node.someAttr throws PropertyNotFoundStrict when the
        attribute is absent, because the module runs under
        Set-StrictMode -Version Latest. Every attribute read in the
        Open-DrawFile parser must go through this helper.
        Returns $Default when the node is not an element or the
        attribute is missing or empty.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)][AllowNull()]$Node,
        [Parameter(Mandatory)][string]$Name,
        [Parameter()][string]$Default = ''
    )

    if ($null -eq $Node -or $Node -isnot [System.Xml.XmlElement]) { return $Default }
    if (-not $Node.HasAttribute($Name))                           { return $Default }

    $v = [string]$Node.GetAttribute($Name)
    if ([string]::IsNullOrEmpty($v)) { return $Default }
    return $v
}

function Get-DrawDiagramModel {
    <#
    .SYNOPSIS
        Returns the <mxGraphModel> element of a <diagram>, decompressing it first
        if the page is stored in draw.io's compressed form.
    .DESCRIPTION
        [FIX-20] A <diagram> holds its page in one of TWO shapes, and draw.io
        writes the compressed one by default on every "Save As" unless the user
        has unticked Extras > Compressed:

            <diagram name="P"><mxGraphModel>...</mxGraphModel></diagram> plain
            <diagram name="P">7VvbcuM2Ev0VPbrK...</diagram> compressed

        Open-DrawFile only ever handled the first. On the second it reached
            $model = $diag.mxGraphModel
        and, because the element's only child is a text node, PowerShell threw
            The property 'mxGraphModel' cannot be found on this object.
        under Set-StrictMode -Version Latest. So the module could not open a
        large class of perfectly ordinary draw.io files, and the error named a
        property rather than the real cause.

        draw.io's own reader is Editor.parseDiagramNode: trim the text content,
        and if anything is left, hand it to Graph.decompress; otherwise use the
        first child element. Graph.decompress is

            a=Graph.stringToArrayBuffer(atob(a));
            b=decodeURIComponent(pako.inflateRaw(a,{to:"string"}));

        i.e. base64 -> RAW deflate (no zlib header, which is what .NET's
        DeflateStream does) -> percent-decode. Graph.compress is the exact
        inverse: encodeURIComponent, deflateRaw, btoa.

        The percent-decode is skipped when the inflated text already starts
        with '<'. That test is exact rather than a guess: encodeURIComponent
        escapes '<' to %3C without exception, so a genuinely URI-encoded
        payload can never begin with one. Running UnescapeDataString over XML
        that was not encoded would corrupt any literal '%' followed by two hex
        digits — a label like "100%AB" would come back as "100<<".

        Returns $null when the diagram is empty, and warns and returns $null
        when the payload is present but cannot be decoded — one unreadable page
        should not cost the caller the other pages in the file.
    #>

    [CmdletBinding()]
    [OutputType([System.Xml.XmlElement])]
    param(
        [Parameter(Mandatory)][AllowNull()]$Diagram,
        [Parameter()][string]$PageName = 'Page'
    )

    if ($null -eq $Diagram -or $Diagram -isnot [System.Xml.XmlElement]) { return $null }

    # Plain form: the model is a child element. SelectSingleNode, not
    # $Diagram.mxGraphModel — the latter is the access that threw.
    $model = $Diagram.SelectSingleNode('mxGraphModel')
    if ($null -ne $model) { return $model }

    $payload = ([string]$Diagram.InnerText).Trim()
    if ([string]::IsNullOrEmpty($payload)) { return $null }   # genuinely empty page

    try {
        $bytes = [System.Convert]::FromBase64String($payload)
    }
    catch {
        Write-Warning ("Open-DrawFile: page '$PageName' has non-XML, non-base64 content " +
                       'and was loaded empty.')
        return $null
    }

    try {
        $ms = [System.IO.MemoryStream]::new($bytes)
        $ds = [System.IO.Compression.DeflateStream]::new(
                  $ms, [System.IO.Compression.CompressionMode]::Decompress)
        $sr = [System.IO.StreamReader]::new($ds, [System.Text.Encoding]::UTF8)
        try   { $text = $sr.ReadToEnd().Trim() }
        finally { $sr.Dispose() }
    }
    catch {
        Write-Warning ("Open-DrawFile: page '$PageName' looks compressed but could not be " +
                       "inflated ($($_.Exception.Message)); it was loaded empty.")
        return $null
    }

    if (-not $text.StartsWith('<')) { $text = [uri]::UnescapeDataString($text) }

    try   { $inner = [xml]$text }
    catch {
        Write-Warning ("Open-DrawFile: page '$PageName' decompressed to something that is " +
                       'not XML; it was loaded empty.')
        return $null
    }

    if ($null -eq $inner.DocumentElement -or
        $inner.DocumentElement.Name -ne 'mxGraphModel') {
        Write-Warning ("Open-DrawFile: page '$PageName' decompressed to " +
                       "<$($inner.DocumentElement.Name)> rather than <mxGraphModel>; " +
                       'it was loaded empty.')
        return $null
    }

    return $inner.DocumentElement
}

# ── Built-in shape index (Data/DrawShapeIndex.json) ──────────────────
# Loaded lazily on first use and cached for the module's lifetime.
$script:DrawShapeIndex = $null   # raw parsed JSON
$script:DrawShapeFlat  = $null   # flattened, searchable list

function Get-DrawShapeIndexPath {
    <#
    .SYNOPSIS
        Path to the generated built-in shape index.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param()
    # [FIX-31] Separate ChildPath arguments, not an embedded '\'. Join-Path
    # does not translate separators inside a path segment — it only joins —
    # and on Linux and macOS a backslash is an ordinary filename character.
    # So 'Data\DrawShapeIndex.json' resolved to a single file literally named
    # "Data\DrawShapeIndex.json", Test-Path said no, and Initialize-DrawShapeIndex
    # threw
    # DrawManagement: shape index not found at '.../Data\DrawShapeIndex.json'.
    # Generate it with Build\Update-DrawShapeIndex.ps1
    # telling the user to regenerate a file that was sitting there the whole
    # time. The manifest claims PSEdition Core with no OS constraint and
    # Install.ps1 documents the Linux and macOS module paths, so this took
    # Find-DrawShape, Get-DrawShapeStyle, Add-DrawShapeByName and
    # Get-DrawShapeIndexInfo — the index feature entirely — off every
    # non-Windows install. PowerShell 7's Join-Path takes additional child
    # paths, which is portable.
    Join-Path $script:ModuleRoot 'Data' 'DrawShapeIndex.json'
}

function Initialize-DrawShapeIndex {
    <#
    .SYNOPSIS
        Loads and flattens the built-in shape index on first use.
    .DESCRIPTION
        [FIX-10] Flattening the three sections (XML stencils, JS-registered
        shapes, SVG icons) into one list with a ready-made Style per entry
        is what makes Find-DrawShape a single wildcard match rather than
        three special cases. Cached, so the ~420 KB JSON is parsed once.
    #>

    [CmdletBinding()]
    param([switch]$Force)

    if ($null -ne $script:DrawShapeFlat -and -not $Force) { return }

    $path = Get-DrawShapeIndexPath
    if (-not (Test-Path -LiteralPath $path)) {
        throw ("DrawManagement: shape index not found at '$path'. " +
               "Generate it with Build\Update-DrawShapeIndex.ps1 (requires a local " +
               "draw.io Desktop install).")
    }

    $script:DrawShapeIndex = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json

    $flat = New-Object 'System.Collections.Generic.List[object]'

    # 1. XML stencils, grouped by library
    foreach ($libProp in $script:DrawShapeIndex.stencils.PSObject.Properties) {
        $lib = $libProp.Name
        foreach ($s in $libProp.Value) {
            $flat.Add([PSCustomObject]@{
                PSTypeName = 'DrawManagement.ShapeIndexEntry'
                Name       = "$lib.$($s.n)"
                Kind       = 'Stencil'
                Library    = $lib
                Width      = [int]$s.w
                Height     = [int]$s.h
                Style      = "shape=$lib.$($s.n);html=1;"
            })
        }
    }

    # 2. Programmatic shapes — these declare no dimensions anywhere
    foreach ($n in $script:DrawShapeIndex.jsShapes) {
        $lib = if ($n -match '^(mxgraph\.[^.]+)') { $Matches[1] } else { 'mxgraph' }
        $flat.Add([PSCustomObject]@{
            PSTypeName = 'DrawManagement.ShapeIndexEntry'
            Name       = $n
            Kind       = 'Shape'
            Library    = $lib
            Width      = 80
            Height     = 80
            Style      = "shape=$n;html=1;"
        })
    }

    # 3. SVG icons
    foreach ($p in $script:DrawShapeIndex.icons) {
        $lib = if ($p -match '^([^/]+)/') { $Matches[1] } else { 'lib' }
        $flat.Add([PSCustomObject]@{
            PSTypeName = 'DrawManagement.ShapeIndexEntry'
            Name       = $p
            Kind       = 'Icon'
            Library    = $lib
            Width      = 68
            Height     = 68
            Style      = ("image;aspect=fixed;html=1;points=[];align=center;" +
                          "fontSize=12;image=img/lib/$p;")
        })
    }

    $script:DrawShapeFlat = $flat
    Write-Verbose ("Initialize-DrawShapeIndex: loaded $($flat.Count) entries " +
                   "(draw.io $($script:DrawShapeIndex.drawioVersion))")
}

# ── Sidebar palette colours (Data/DrawPaletteColors.json) ─────────────
# The shape index records names and sizes only. Many libraries (vvd,
# veeam2, azure, office, aws4, ...) draw their glyph with the FILL colour
# and no outline, so a bare 'shape=mxgraph.vvd.server;' renders with
# draw.io's defaults — white fill, black stroke — and looks like a broken
# outline. These are the colours draw.io's own sidebar applies on drag.
$script:DrawPaletteColors = $null

function Get-DrawPaletteColor {
    <#
    .SYNOPSIS
        Returns draw.io's sidebar colours for a stencil, or $null.
    .DESCRIPTION
        An ordered dictionary of colour keys (fillColor, strokeColor,
        gradientColor, gradientDirection) for the shape. A missing data file
        is not an error: shapes simply keep draw.io's default colours.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][string] $ShapeName)

    if ($null -eq $script:DrawPaletteColors) {
        $path = Join-Path $script:ModuleRoot 'Data' 'DrawPaletteColors.json'
        $script:DrawPaletteColors = @{}
        if (Test-Path -LiteralPath $path) {
            try {
                $doc = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable
                if ($doc.ContainsKey('shapes')) { $script:DrawPaletteColors = $doc['shapes'] }
            }
            catch {
                Write-Warning "DrawManagement: could not read palette colours from '$path' — $_"
            }
        }
    }

    if ($script:DrawPaletteColors.ContainsKey($ShapeName)) {
        return $script:DrawPaletteColors[$ShapeName]
    }
    return $null
}

function Get-DrawFitSize {
    <#
    .SYNOPSIS
        Scales a natural Width x Height, keeping its aspect ratio.
    .DESCRIPTION
        -Size fits the longest side to that many pixels. -Width or -Height
        alone fixes that side and derives the other. Both, or neither,
        return them unchanged (neither -> the natural size).
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][double] $NaturalWidth,
        [Parameter(Mandatory)][double] $NaturalHeight,
        [double] $Size   = 0,
        [double] $Width  = 0,
        [double] $Height = 0
    )
    $nw = [Math]::Max(1, $NaturalWidth)
    $nh = [Math]::Max(1, $NaturalHeight)

    if ($Size -gt 0) {
        $k = $Size / [Math]::Max($nw, $nh)
        return [PSCustomObject]@{
            Width  = [Math]::Max(1, [Math]::Round($nw * $k))
            Height = [Math]::Max(1, [Math]::Round($nh * $k))
        }
    }
    if ($Width -gt 0 -and $Height -gt 0) { return [PSCustomObject]@{ Width = $Width; Height = $Height } }
    if ($Width -gt 0) {
        return [PSCustomObject]@{ Width = $Width; Height = [Math]::Max(1, [Math]::Round($nh * $Width / $nw)) }
    }
    if ($Height -gt 0) {
        return [PSCustomObject]@{ Width = [Math]::Max(1, [Math]::Round($nw * $Height / $nh)); Height = $Height }
    }
    return [PSCustomObject]@{ Width = $nw; Height = $nh }
}

function ConvertTo-DrawImageStyleUri {
    <#
    .SYNOPSIS
        Converts a canonical data: URI into the form a draw.io STYLE accepts.
    .DESCRIPTION
        [FIX-18] A style string is parsed by splitting on ';' and then on
        the first '=' — mxGraph has no quoting and no escaping. A standard
        data URI carries its own ';' before 'base64', so

            image=data:image/png;base64,iVBORw0KGgo...

        tokenises into TWO entries: image='data:image/png' (a truncated URI
        that resolves to nothing) plus a junk key 'base64,iVBORw0KGgo...'.
        The shape renders as an empty box and nothing reports an error —
        the same silent failure class as an unknown shape= name.

        draw.io writes a COMMA where the ';base64,' would go:

            image=data:image/png,iVBORw0KGgo...

        and restores it on load, in mxGraph.prototype.postProcessCellStyle:

            c = a.indexOf(",");
            if (0 < c && ";base64," != a.substring(c - 7, c + 1))
                a = a.substring(0, c) + ";base64," + a.substring(c + 1);

        The comma form is therefore wrong ONLY inside a style string. It
        stays canonical everywhere else — DrawStencil.ToLibraryEntry's
        'data' field is JSON, not a style, and must keep the standard URI
        or draw.io's library loader will reject it.

        A URI that is not 'data:<mime>;base64,<payload>' (an http(s) URL, or
        one already in comma form) is returned unchanged.
    .EXAMPLE
        ConvertTo-DrawImageStyleUri 'data:image/png;base64,iVBOR'
        # data:image/png,iVBOR
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)][AllowEmptyString()][string]$Uri
    )
    process {
        if ([string]::IsNullOrWhiteSpace($Uri)) { return '' }
        # [^;,]* keeps this anchored to the MIME type, so a URI carrying
        # extra parameters (data:image/png;charset=x;base64,...) does not
        # match and is passed through rather than mangled.
        if ($Uri -match '^(data:[^;,]*);base64,(.*)$') {
            return "$($Matches[1]),$($Matches[2])"
        }
        return $Uri
    }
}

function Join-DrawStyle {
    <#
    .SYNOPSIS
        Appends a fragment to a draw.io style string, safely.
    .DESCRIPTION
        [FIX-01] Style fragments MUST be appended with no space after the
        separating ';'. mxGraph parses a style by splitting on ';' and
        taking the text before '=' as the key verbatim — it does not trim.
        A leading space turns 'fillColor' into ' fillColor', which the
        renderer does not recognise, so the setting is silently dropped.
        draw.io itself never emits a space after ';' in a style string.

        Also inserts the separator when the existing style is missing its
        trailing ';', so 'ellipse;html=1' + 'fillColor=#fff;' does not
        collapse into 'html=1fillColor=#fff;'.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter()][string]$Style,
        [Parameter(Mandatory)][string]$Fragment
    )

    $s = ([string]$Style).TrimEnd()
    if ($s -and -not $s.EndsWith(';')) { $s += ';' }
    return $s + $Fragment
}

function New-DrawBounds {
    <#
    .SYNOPSIS
        Builds the bounds object every Set-Draw*Layout function returns.
    .DESCRIPTION
        Right/Bottom are precomputed so callers can size a parent container
        around a finished layout without repeating the arithmetic.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory)][double]$X,
        [Parameter(Mandatory)][double]$Y,
        [Parameter(Mandatory)][double]$Width,
        [Parameter(Mandatory)][double]$Height
    )

    [PSCustomObject]@{
        PSTypeName = 'DrawManagement.Bounds'
        X          = $X
        Y          = $Y
        Width      = $Width
        Height     = $Height
        Right      = $X + $Width
        Bottom     = $Y + $Height
    }
}

function Measure-DrawColumnHeight {
    <#
    .SYNOPSIS
        Total stacked height of a column of cells, including the gaps.
    #>

    [CmdletBinding()]
    [OutputType([double])]
    param(
        [Parameter(Mandatory)][AllowEmptyCollection()][DrawCell[]]$Cell,
        [Parameter()][double]$Gap = 0
    )

    if ($Cell.Count -eq 0) { return 0.0 }
    [double]$sum = 0
    foreach ($c in $Cell) { $sum += $c.Height }
    return $sum + ($Cell.Count - 1) * $Gap
}

function Get-DrawObjectProperty {
    <#
    .SYNOPSIS
        Reads a property off an arbitrary object without tripping StrictMode.
    .DESCRIPTION
        [FIX-08] The Azure functions are duck-typed — they accept whatever
        Get-AzResource hands back, plus hashtables and PSCustomObjects in
        tests. Under Set-StrictMode -Version Latest a plain $obj.Missing
        throws, so every such read goes through here.
        Returns $Default when the object is null or has no such member.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][AllowNull()]$InputObject,
        [Parameter(Mandatory)][string]$Name,
        [Parameter()]$Default = $null
    )

    if ($null -eq $InputObject) { return $Default }

    if ($InputObject -is [System.Collections.IDictionary]) {
        if ($InputObject.Contains($Name)) { return $InputObject[$Name] }
        return $Default
    }

    $member = $InputObject.PSObject.Properties[$Name]
    if ($null -eq $member) { return $Default }

    try   { return $member.Value }
    catch { return $Default }
}

function ConvertFrom-UserObjectAttr {
    <#
    .SYNOPSIS
        Extracts custom metadata from a UserObject wrapper element.
    .DESCRIPTION
        [FIX-06] Every attribute except the structural ones (label, id,
        tooltip, link, placeholders) is a user-defined property, and is
        returned as a hashtable so Open-DrawFile can restore
        DrawCell.Metadata / DrawEdge.Metadata on round-trip.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory)][AllowNull()]$Wrapper
    )

    $meta = @{}
    if ($null -eq $Wrapper -or $Wrapper -isnot [System.Xml.XmlElement]) { return $meta }

    $structural = @('label', 'id', 'tooltip', 'link', 'placeholders')
    foreach ($attr in $Wrapper.Attributes) {
        if ($structural -contains $attr.Name) { continue }
        $meta[$attr.Name] = [string]$attr.Value
    }
    return $meta
}

function Resolve-CellId {
    <#
    .SYNOPSIS
        Resolves a cell reference — accepts a DrawCell object or a string ID.
    .DESCRIPTION
        [HELP-08] Explicit type check — [DrawEdge] is not accepted here;
        only [DrawCell] and [string] are valid inputs.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]$Ref
    )

    if ($Ref -is [DrawCell]) {
        if ([string]::IsNullOrWhiteSpace($Ref.Id)) {
            throw "Resolve-CellId: the supplied DrawCell has an empty Id."
        }
        return $Ref.Id
    }

    if ($Ref -is [string]) {
        if ([string]::IsNullOrWhiteSpace($Ref)) {
            throw "Resolve-CellId: cell ID string must not be null or empty."
        }
        return $Ref
    }

    throw ("Resolve-CellId: expected a [DrawCell] or a [string] ID, " +
           "but received [$($Ref.GetType().FullName)]. " +
           "Pass the cell object directly or its .Id property.")
}