package visualizer

import (
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	
	d2log 
	d2png 
	

	
	amgraph 
	am 
)

var (
	colorRelRemove  = "#DA70D6"
	colorRelAdd     = "orange"
	colorRelRequire = "lightblue"
	colorSelected   = "limegreen"
	colorActiveBg   = "yellow"
	// colorReadyFg    = "black"
	colorReadyBg = "deepskyblue"
	// colorStartFg    = "black"
	colorStartBg = "#329241"
	colorErrBg   = "red"
	// colorErrFg      = "black"
)

// TODO color vars, use in update func
var d2Header = utils.Sp(`
	vars: {
		d2-config: {
			theme-id: 201
			theme-overrides: {
				N7: black

				# mach border
				B1: "#5F5C5C"
				B2: grey
				B3: "#6C7086"
				# mach background
				B4: "#262424"
				B5: "#45475A"
				B6: "#313244"

				AA2: "#f38BA8"
				AA4: "#45475A"
				AA5: "#313244"

				AB4: "#45475A"
				AB5: "#313244"
			}
		}
	}
	classes: {
		# active
		_1: {
			style: {
				font-color: black
				fill: yellow
				border-radius: 999
				double-border: true
			}
		}
		# inactive
		_0: {
			style: {
				stroke: white
				border-radius: 999
				double-border: true
			}
		}

		# active inherited
		_1i: {
			style: {
				font-color: black
				fill: "` + colorActiveBg + `"
				border-radius: 999
			}
		}
		# inactive inherited
		_0i: {
			style: {
				border-radius: 999
			}
		}

		# active Start
		_1s: {
			style: {
				font-color: black
				fill: "` + colorStartBg + `"
				border-radius: 999
			}
		}
		# inactive Start
		_0s: {
			style: {
				border-radius: 999
			}
		}

		# active Ready
		_1r: {
			style: {
				font-color: black
				fill: "` + colorReadyBg + `"
				border-radius: 999
			}
		}
		# inactive Ready
		_0r: {
			style: {
				border-radius: 999
			}
		}

		# require relation
		req: {
			style.stroke: "` + colorRelRequire + `"
			target-arrowhead.style.filled: true
			target-arrowhead.shape: circle
		}
		# add relation
		add: {
			style.stroke: "` + colorRelAdd + `"
			target-arrowhead.shape: triangle
			target-arrowhead.style.filled: true
		}
		# remove relation
		rem: {
			style.stroke: "` + colorRelRemove + `"
			style.stroke-width: 2
			target-arrowhead.style.filled: true
			target-arrowhead.shape: diamond
			source-arrowhead.style.filled: true
			source-arrowhead.shape: diamond
		}
		# double remove relation
		rem2: {
			style.stroke: "` + colorRelRemove + `"
			style.stroke-width: 3
			target-arrowhead.style.filled: true
			target-arrowhead.shape: diamond
			source-arrowhead.style.filled: true
			source-arrowhead.shape: diamond
		}
		# add pipe
		pipe_add: {
			style.stroke: "` + colorRelAdd + `"
			style.stroke-dash: 3
			target-arrowhead.style.filled: false
		}
		# remove pipe
		pipe_rem: {
			style.stroke: "` + colorRelRemove + `"
			target-arrowhead.shape: diamond
			style.stroke-dash: 3
		}
		# pipe (mach -> mach)
		pipe: {
			style.stroke: white
		}

		# parent hierarchy relation
		parent: {
			style.stroke: white
			style.stroke-width: 8
			target-arrowhead.shape: circle
		}
		mach: {
      style: {
				font-size: 50
				fill: "black"
				border-radius: 40
				stroke-width: 4
			}
			label.near: top-center
		}
		state: {
      style.font-size: 30
		}
		called: {
			style.stroke-width: 10
			style.stroke: "white"
			style.stroke-dash: 3
		}
		handler: {
			style.stroke: "#2596be"
		}
		cancel: {
			style: {
				stroke: red
				stroke-width: 5
			}
		}
		state-zoom: {
			style: {
				font-size: 50
				stroke-width: 10
			}
		}
		rel-zoom: {
			style.stroke-width: 10
		}
		rpc: {
			style: {
				# TODO dedicated color
				stroke: "` + colorRelAdd + `"
				stroke-width: 4
			}
		}
	  lifeline: {
	    style.stroke: grey
	  }

	#${CLASSES}
	}
	direction: right

	`)

func ( *Renderer) ( context.Context) error {
	.log("Generating D2 %s", .OutputFilename)

	.cleanBuffer()

	var  error
	.adjMap = .graph.AdjacencyMap()

	// state classes
	 := ""
	for ,  := range .graph.Machines {
		if !.shouldRenderMach(.ID) {
			continue
		}
		 += "\tM_" + .ID + ": {}\n"
		for ,  := range .StateNames {
			// TODO optimize: use short names, save index as *-index.txt
			 += "\tF_" +  + ": {}\n"
			 += "\tT_" +  + ": {}\n"
		}
	}

	// header
	.buf.WriteString(strings.ReplaceAll(d2Header, "#${CLASSES}", ))

	// 1st pass - requested machs and neighbours
	for  := range .adjMap {
		if .Err() != nil {
			return .Err()
		}

		,  := .graph.Vertex()
		if  != nil {
			return fmt.Errorf("failed to get vertex for source %s: %w", , )
		}

		// render machines
		if .StateName == "" {
			 = .outputD2Mach(, .MachId)
			if  != nil {
				return fmt.Errorf("failed to render D2 mach %s: %w", , )
			}
		}
	}

	// collect what was rendered
	 := slices.Collect(maps.Keys(.renderedMachs))

	// 2nd pass - render adjecents as halfs
	 := .adjsMachsToRender
	for ,  := range  {
		if .Err() != nil {
			return .Err()
		}

		// only not already rendered
		if ,  := .renderedMachs[];  {
			continue
		}

		 = .outputD2HalfMach(, )
		if  != nil {
			return fmt.Errorf("failed to render D2 half mach %s: %w", , )
		}
	}

	// 3rd pass - render predecesors as halfs
	 := len(.RenderMachs) > 0 || len(.RenderMachsRe) > 0
	 := .RenderPipes && .RenderHalfPipes ||
		.RenderConns && .RenderHalfConns ||
		.RenderParentRel && .RenderHalfHierarchy

	if  &&  {
		 := .graph.PredecessorMap()
		for ,  := range  {
			if .Err() != nil {
				return .Err()
			}

			for  := range [] {
				,  := .graph.Vertex()
				if  != nil {
					return 
				}
				// machs only
				if .StateName != "" {
					continue
				}
				// only if not already rendered
				if ,  := .renderedMachs[];  {
					continue
				}

				 = .outputD2HalfMach(, )
				if  != nil {
					return fmt.Errorf("failed to render D2 half mach %s: %w", , )
				}
			}
		}
	}

	// build str diag
	 := .buf.String()

	// generate D2
	.log("Generating %s.d2\n", .OutputFilename)
	 = os.WriteFile(.OutputFilename+".d2", []byte(), 0o644)
	if  != nil {
		return fmt.Errorf("failed to write D2 file: %w", )
	}

	// generate D2 graph
	// none - only the .d2 source was requested
	if .OutputD2Layout == D2LayoutNone {
		.log("Skipping D2 layout (%s)\n", D2LayoutNone)
		return nil
	}

	.log("Generating %s.svg (%s)\n", .OutputFilename, .OutputD2Layout)
	, , ,  := compileD2(
		, , .OutputD2Layout)
	if  != nil {
		return 
	}
	.log("Edges: %d Objects: %d\n", len(.Edges), len(.Objects))

	// render svg
	if .OutputD2Svg {
		,  := d2svg.Render(, )
		if .Err() != nil {
			return .Err()
		}
		if  != nil {
			return fmt.Errorf("failed to render D2: %w", )
		}

		 = os.WriteFile(filepath.Join(.OutputFilename+".svg"), , 0o600)
		if  != nil {
			return fmt.Errorf("failed to write D2 file: %w", )
		}
		.log("Generated %s.svg\n", .OutputFilename)
	}

	if .OutputPng {
		if  := .outputD2Png(, , );  != nil {
			return fmt.Errorf("failed to render PNG: %w", )
		}
	}

	return nil
}

// compileD2 compiles a D2 source using the given layout engine.
func compileD2(
	 context.Context,  string,  D2Layout,
) (*d2target.Diagram, *d2graph.Graph, *d2svg.RenderOpts, error) {
	// Initialize the slog logger
	 := slog.HandlerOptions{
		AddSource: true,           // Include source file and line number
		Level:     slog.LevelInfo, // Set default log level
	}

	 := slog.New(slog.NewJSONHandler(os.Stdout, &))
	 = d2log.With(, )
	,  := textmeasure.NewRuler()
	 := string()
	 := func( string) (d2graph.LayoutGraph, error) {
		switch D2Layout(strings.ToLower()) {
		case D2LayoutTala:
			return d2talalayout.DefaultLayout, nil
		case D2LayoutDagre:
			return d2dagrelayout.DefaultLayout, nil
		default:
			return d2elklayout.DefaultLayout, nil
		}
	}
	 := func( string) (d2graph.RouteEdges, error) {
		if D2Layout(strings.ToLower()) == D2LayoutTala {
			return d2talalayout.RouteEdges, nil
		}
		return nil, nil
	}
	 := &d2svg.RenderOpts{
		Pad:     go2.Pointer(int64(5)),
		ThemeID: &d2themescatalog.DarkMauve.ID,
	}
	 := &d2lib.CompileOptions{
		Layout:         &,
		LayoutResolver: ,
		RouterResolver: ,
		Ruler:          ,
		// the input is generated by us (trusted), so relax the secure defaults
		// meant for untrusted user input
		MaxVariableExpansion: d2MaxVariableExpansion,
		MaxGlobExpansion:     d2MaxGlobExpansion,
		MaxEdgeExpansion:     d2MaxEdgeExpansion,
		MaxEdgeExpansionWork: d2MaxEdgeExpansionWork,
	}

	, ,  := d2lib.Compile(, ,
		, )
	if .Err() != nil {
		return nil, nil, nil, .Err()
	}
	if  != nil {
		return nil, nil, nil, fmt.Errorf("failed to compile D2: %w", )
	}

	return , , , nil
}

// D2 compiler work budgets for am-vis generated (trusted) diagrams. The secure
// defaults (64 KiB) are calibrated for untrusted user input and are too low for
// larger generated graphs.
const (
	d2MaxVariableExpansion = 1_000_000_000
	d2MaxGlobExpansion     = 100_000_000
	d2MaxEdgeExpansion     = 1_000_000
	d2MaxEdgeExpansionWork = 100_000_000
)

// Raster limits mirror the d2 CLI's production safety ceilings, so oversized
// diagrams fail with a clear error instead of exhausting memory.
const (
	d2PngMaxDimension    = 32_768
	d2PngMaxPixels       = 64 * 1024 * 1024
	d2PngMaxNodes        = 1_000_000
	d2PngMaxDepth        = 1_024
	d2PngMaxPathCommands = 10_000_000
	d2PngMaxTextRunes    = 100_000
	d2PngMaxCoverage     = 10_000_000
	d2PngMaxShapingRuns  = 100_000
	d2PngMaxAssets       = 4_096
	d2PngMaxAssetBytes   = 512 * 1024 * 1024
	d2PngMaxOffscreen    = 512 * 1024 * 1024
	d2PngMaxEvenOddWork  = 250_000_000
	d2PngMaxScanlineWork = 4_000_000_000
	d2PngMaxAnimTracks   = 1_000_000
	d2PngMaxAnimKeyframe = 10_000_000
)

// outputD2Png rasterizes a compiled D2 diagram into a PNG via d2's native
// pure-Go renderer (no browser required).
func ( *Renderer) (
	 context.Context,  *d2target.Diagram,  *d2svg.RenderOpts,
) error {
	.log("Generating %s.png\n", .OutputFilename)

	// single-board export: no child boards get composed into this frame
	 := *
	.Layers = nil
	.Scenarios = nil
	.Steps = nil

	,  := d2scenebuild.Build(, &, d2scenebuild.Options{
		Pad:             .Pad,
		Scale:           .Scale,
		Center:          .Center,
		ThemeID:         .ThemeID,
		ThemeOverrides:  .ThemeOverrides,
		MaxNodes:        d2PngMaxNodes,
		MaxPathCommands: d2PngMaxPathCommands,
		Sketch:          .Sketch != nil && *.Sketch,
		SketchBudget: d2scenebuild.SketchBudget{
			MaxOperationSets: d2PngMaxNodes,
			MaxOperations:    d2PngMaxPathCommands,
			MaxPathCommands:  d2PngMaxPathCommands,
		},
		Appendix: true,
	})
	if .Err() != nil {
		return .Err()
	}
	if  != nil {
		return fmt.Errorf("failed to build the D2 scene: %w", )
	}

	// fit large diagrams below the frame limits without upscaling (0.99 leaves
	// room for the renderer's per-axis rounding)
	 := 1.0
	if ,  := .LogicalWidth, .LogicalHeight;  > 0 &&  > 0 {
		if  := 0.99 * math.Sqrt(float64(d2PngMaxPixels)/(*));  <  {
			 = 
		}
		if  := float64(d2PngMaxDimension) / max(, );  <  {
			 = 
		}
	}

	,  := d2raster.Render(, , d2raster.FrameOptions{
		Scale:                 ,
		Background:            color.White,
		MaxWidth:              d2PngMaxDimension,
		MaxHeight:             d2PngMaxDimension,
		MaxPixels:             d2PngMaxPixels,
		MaxNodes:              d2PngMaxNodes,
		MaxDepth:              d2PngMaxDepth,
		MaxPathCommands:       d2PngMaxPathCommands,
		MaxTextRunesPerRun:    d2PngMaxTextRunes,
		MaxFontFacesPerText:   d2PngMaxAssets,
		MaxTextCoverageChecks: d2PngMaxCoverage,
		MaxTextShapingRuns:    d2PngMaxShapingRuns,
		MaxAssets:             d2PngMaxAssets,
		MaxAssetBytes:         d2PngMaxAssetBytes,
		MaxDecodedAssetBytes:  d2PngMaxAssetBytes,
		MaxImportDepth:        d2PngMaxDepth,
		MaxOffscreenBytes:     d2PngMaxOffscreen,
		MaxEvenOddClipWork:    d2PngMaxEvenOddWork,
		MaxScanlineWork:       d2PngMaxScanlineWork,
		MaxAnimationTracks:    d2PngMaxAnimTracks,
		MaxAnimationKeyframes: d2PngMaxAnimKeyframe,
	})
	if .Err() != nil {
		return .Err()
	}
	if  != nil {
		return fmt.Errorf("failed to rasterize the D2 scene: %w", )
	}

	var  bytes.Buffer
	if  := png.Encode(&, );  != nil {
		return fmt.Errorf("failed to encode PNG: %w", )
	}

	,  := d2png.AddExif(.Bytes())
	if  != nil {
		return fmt.Errorf("failed to add exif to png: %w", )
	}

	return os.WriteFile(.OutputFilename+".png", , 0o600)
}

func ( *Renderer) ( context.Context,  string) error {
	// blacklist
	if slices.Contains(.RenderSkipMachs, ) {
		return nil
	}

	// whitelist & neighbours
	if !.shouldRenderMach() {
		return nil
	}
	// render once
	if ,  := .renderedMachs[];  {
		return nil
	}
	.renderedMachs[] = struct{}{}

	// TAGS
	,  := .graph.Machines[]
	if ! {
		// TODO fix with virtual machine placeholders
		return nil
		// return fmt.Errorf("failed to get client for mach %s", machId)
	}

	 := "\n"
	if .RenderTags && len(.Tags) > 0 {
		 := "#" + strings.Join(.Tags, "\n#")
		 = "\texplanation: |text\n\t\tTags\n" +  +
			"\n\t| { style.stroke: transparent }\n\n"
	}

	// PARENT NESTING
	 := .shortId()
	if .RenderNestSubmachines {
		// TODO fix non-rendered machines in the nested ID (remove? when?)
		 = strings.Join(.fullIdPath(, true), ".")
	}
	 := ""
	// TODO class
	if slices.Contains(.renderMachIds(), ) {
		 = "\tstyle.stroke: yellow\n"
	} else if len(.renderMachIds()) > 0 {
		 = "\tstyle.stroke: white\n"
	}
	 := ": " + 
	if !.RenderMachTitles {
		 = `: ""`
	}
	.buf.WriteString( +  + " {\n" +
		"\tclass: [M_" +  + "; mach]\n" +
		 + )

	 := ""
	 := ""
	 := ""
	 := map[string]struct{}{}
	// TODO extract & split
	for ,  := range .adjMap[] {
		if .Err() != nil {
			return .Err()
		}

		,  := .graph.Vertex(.Target)
		if  != nil {
			return fmt.Errorf("failed to get vertex for target %s: %w",
				.Target, )
		}
		 := .Properties.Data.(*amgraph.EdgeData)
		 := .StateName

		// STATES TODO extract
		if  != "" && (.shouldRenderState(, ) ||
			.RenderPipeStates && .stateHasRenderedPipes(, )) {

			// TODO enum for classes
			 := .shortId()
			 := "_0"
			if .RenderActive {
				 := slices.Index(.StateNames, )
				// TODO current mach time, not latest
				if .Time.Is1() {
					 = "_1"
				}
			}

			// INHERITED
			 := IsStateInherited(, .StateNames)
			 := ""
			if .RenderMarkInherited &&  {
				 += "i"
			}

			// START & READY
			if .RenderReady &&  == am.StateReady {
				 = "r"
			} else if .RenderStart &&  == am.StateStart {
				 = "s"
			}

			if slices.Contains(.RenderZoom, ) {
				 += "; state-zoom"
			}

			.buf.WriteString("\t" +  + ":" +  + "\n")
			.buf.WriteString("\t" +  + ".class: [state; " +
				 +  + "]" + "\n")

			.renderD2Relations(, , )
		}

		 += .renderD2Parent(, , , .RenderHalfHierarchy,
			false)
		 += .renderD2Pipes(, , , .RenderHalfPipes, false)
		 += .renderD2Conns(, , , .RenderHalfConns, false)
	}

	.buf.WriteString("}\n")

	if  != "" {
		.buf.WriteString()
	}

	if  != "" {
		.buf.WriteString()
	}

	if  != "" {
		.buf.WriteString()
	}

	.buf.WriteString("\n\n")

	return nil
}

func ( *Renderer) (
	 context.Context,  string,
) error {
	.renderedMachs[] = struct{}{}
	 := .shortId()
	if .RenderNestSubmachines {
		 = strings.Join(.fullIdPath(, true), ".")
	}
	 := ": " + 
	if !.RenderMachTitles {
		 = `: ""`
	}
	.buf.WriteString( +  + " {\n" +
		"\tclass: [M_" +  + "; mach]\n")

	 := ""
	 := ""
	 := ""
	for ,  := range .adjMap[] {
		if .Err() != nil {
			return .Err()
		}

		,  := .graph.Connection(, .Target)
		if  != nil {
			return 
		}
		 := .Target
		 := .Edge

		 += .renderD2Parent(, , , false, true)
		 += .renderD2Pipes(, , , false, true)
		 += .renderD2Conns(, , , false, true)
	}

	.buf.WriteString("}\n")

	if  != "" {
		.buf.WriteString()
	}

	if  != "" {
		.buf.WriteString()
	}

	if  != "" {
		.buf.WriteString()
	}

	.buf.WriteString("\n\n")

	return nil
}

func ( *Renderer) (
	 string,  string,  map[string]struct{},
) {
	 := .shortId()
	 := .graph.Machines[]
	 := .Schema[]

	if !.RenderRelations {
		return
	}

	 := fmt.Sprintf("[M_%s; F_%s; T_", .ID, )

	// require
	for ,  := range .Require {
		if !.shouldRenderState(, ) {
			continue
		}

		 := ""
		if slices.Contains(.RenderZoom, ) ||
			slices.Contains(.RenderZoom, ) {

			 += "; rel-zoom"
		}

		 :=  +  + "; " + "req" +  + "]\n"
		.buf.WriteString("\t" +  + " --> " +
			.shortId() + ": require {\n" +
			"\t\tclass: " +  +
			"\t}\n")
	}

	// add
	for ,  := range .Add {
		if !.shouldRenderState(, ) {
			continue
		}
		 := ""
		if slices.Contains(.RenderZoom, ) ||
			slices.Contains(.RenderZoom, ) {

			 += "; rel-zoom"
		}

		 :=  +  + "; " + "add" +  + "]\n"
		.buf.WriteString("\t" +  + " --> " +
			.shortId() + ": add {\n" +
			"\t\tclass: " +  +
			"\t}\n")
	}

	// TODO "after" relation

	// remove
	for ,  := range .Remove {
		if !.shouldRenderState(, ) {
			continue
		}
		 := ""
		if slices.Contains(.RenderZoom, ) ||
			slices.Contains(.RenderZoom, ) {

			 += "; rel-zoom"
		}

		// no self removal
		if  ==  {
			continue
		}

		// merge double remove
		 := " --> "
		 := "remove"
		 := "rem"
		if slices.Contains(.Schema[].Remove, ) {
			,  := [+":"+]
			,  := [+":"+]
			if  ||  {
				continue
			}
			 = " <--> "
			 = "double remove"
			// not when zoomed in
			if !slices.Contains(.RenderZoom, ) {
				 = "rem2"
			}

			// mark
			[+":"+] = struct{}{}
			[+":"+] = struct{}{}
		}
		 :=  +  + "; " +  +  + "]\n"

		.buf.WriteString("\t" +  +  +
			.shortId() + ": " +  + " {\n" +
			"\t\tclass: " +  +
			"\t}\n")
	}
}

func ( *Renderer) (
	 *amgraph.EdgeData,  string,  *amgraph.Vertex, ,
	 bool,
) string {
	 := ""
	 := .shortId()
	 := .shortId(.MachId)
	if .RenderNestSubmachines {
		 = strings.Join(.fullIdPath(.MachId, true), ".")
		 = strings.Join(.fullIdPath(, true), ".")
	}

	if .RenderNestSubmachines || !.RenderParentRel || !.MachChildOf {
		return 
	}

	// render halfs
	if !.shouldRenderMach(.MachId) && ! {
		return ""
	}

	// render once
	 :=  + ":" + 
	if ,  := .renderedParents[];  {
		return ""
	}
	.renderedParents[] = struct{}{}

	// render this half later
	.adjsMachsToRender = append(.adjsMachsToRender, .MachId)

	return  + " -> " +  +
		": parent { class: parent }\n"
}

// RPC conns
func ( *Renderer) (
	 *amgraph.EdgeData,  string,  *amgraph.Vertex, ,
	 bool,
) string {
	 := ""
	 := .shortId()
	 := .shortId(.MachId)
	if .RenderNestSubmachines {
		 = strings.Join(.fullIdPath(.MachId, true), ".")
		 = strings.Join(.fullIdPath(, true), ".")
	}

	if !.RenderConns || !.MachConnectedTo {
		return 
	}

	// render halfs
	if !.shouldRenderMach(.MachId) && ! {
		return ""
	}

	// render once
	 :=  + ":" + 
	if ,  := .renderedConns[];  {
		return ""
	}
	 +=  + " -> " +  + ": rpc {\n" +
		"\tclass: rpc\n" +
		"}\n"

	// render this half later
	.adjsMachsToRender = append(.adjsMachsToRender, .MachId)

	// remember
	.renderedConns[] = struct{}{}

	return 
}

func ( *Renderer) (
	 *amgraph.EdgeData,  string,  *amgraph.Vertex, ,
	 bool,
) string {
	if !.RenderPipes ||  == .MachId {
		return ""
	}

	 := ""
	 := .shortId()
	 := .shortId(.MachId)
	if .RenderNestSubmachines {
		 = strings.Join(.fullIdPath(.MachId, true), ".")
		 = strings.Join(.fullIdPath(, true), ".")
	}

	for ,  := range .MachPipesTo {
		// mach.state -> mach.state
		if .RenderDetailedPipes {
			 :=  + "." + .shortId(.FromState)
			 :=  + "." + .shortId(.ToState)

			// check the source state
			if !.shouldRenderState(, .FromState) &&
				(!.RenderPipeStates ||  ||
					!.shouldRenderMach(.MachId)) {

				if ! && !.shouldRenderMach() &&
					!.shouldRenderMach(.MachId) {
					continue
				}

				// point from the current machine (not state)
				 = 
			}

			// check the target state
			if !.shouldRenderState(.MachId, .ToState) {
				if .shouldRenderState(, .FromState) &&
					(!.RenderPipeStates || ) {

					// pass (full target render)
				} else if ! && !.shouldRenderMach(.MachId) &&
					!.shouldRenderMach(.MachId) {

					continue
				} else {
					// point to the target machine (not state)
					 = 

					// render this half later
					.adjsMachsToRender = append(.adjsMachsToRender, .MachId)
				}
			}

			// render once
			if ,  := .renderedPipes[+":"+];  {
				continue
			}

			 := "add"
			 := "pipe_add"
			if .MutType == am.MutationRemove {
				 = "remove"
				 = "pipe_rem"
			}
			 +=  + " -> " +  + ":" +  + " {\n" +
				"\tclass: " +  + "\n}\n"

			// remember
			.renderedPipes[+":"+] = struct{}{}

		} else {
			// mach -> mach
			 := 
			if !.shouldRenderMach(.MachId) {
				if ! && !.shouldRenderMach(.MachId) {
					continue
				}
			}

			// render once
			if ,  := .renderedPipes[+":"+];  {
				continue
			}

			 +=  + " -> " +  + ": pipes { class: pipe }\n"

			// remember
			.renderedPipes[+":"+] = struct{}{}
		}
	}

	return 
}