package query import ( "fmt" "io" "math" "sort" "strings" "time" ) type svgTheme struct { bg string border string borderWidth int titleColor string latestColor string lineColor string areaColor string areaOpacity float64 gridColor string axisColor string tickColor string labelColor string sublabelColor string fontFamily string monoFontFamily string } func getSVGTheme(name string) svgTheme { if name == "dark" { return svgTheme{ bg: "#18181b", border: "#27272a", borderWidth: 0, titleColor: "#f4f4f5", latestColor: "#38bdf8", lineColor: "#38bdf8", areaColor: "#38bdf8", areaOpacity: 0.25, gridColor: "#27272a", axisColor: "#3f3f46", tickColor: "#52525b", labelColor: "#a1a1aa", sublabelColor: "#71717a", fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif", monoFontFamily: "monospace", } } // Light high-contrast theme matching default.css return svgTheme{ bg: "#ffffff", border: "#000000", borderWidth: 1, titleColor: "#000000", latestColor: "#000000", lineColor: "#000000", areaColor: "#000000", areaOpacity: 0.08, gridColor: "#e0e0e0", axisColor: "#000000", tickColor: "#000000", labelColor: "#000000", sublabelColor: "#444444", fontFamily: "Arial, sans-serif", monoFontFamily: "Menlo, monospace", } } // RenderSVG writes a self-contained, responsive SVG line chart directly to the writer. // Does not require any external JavaScript libraries. func RenderSVG(w io.Writer, title string, timestamps []int64, values []float64, width, height int, theme ...string) error { selectedTheme := "light" if len(theme) > 0 && theme[0] != "" { selectedTheme = theme[0] } th := getSVGTheme(selectedTheme) if width <= 0 { width = 600 } if height <= 0 { height = 200 } var rectAttr string if th.borderWidth > 0 { rectAttr = fmt.Sprintf(`fill="%s" stroke="%s" stroke-width="%d" rx="4"`, th.bg, th.border, th.borderWidth) } else { rectAttr = fmt.Sprintf(`fill="%s" rx="6"`, th.bg) } if len(timestamps) == 0 || len(values) == 0 { _, err := fmt.Fprintf(w, ` No data `, width, height, width, height, rectAttr, th.sublabelColor, th.monoFontFamily) return err } minVal := values[0] maxVal := values[0] for _, v := range values { if v < minVal { minVal = v } if v > maxVal { maxVal = v } } if minVal == maxVal { maxVal += 1.0 minVal -= 1.0 } paddingLeft := 60.0 paddingRight := 25.0 paddingTop := 35.0 paddingBottom := 42.0 plotW := float64(width) - paddingLeft - paddingRight plotH := float64(height) - paddingTop - paddingBottom if plotW <= 0 { plotW = 100 } if plotH <= 0 { plotH = 50 } minTS := float64(timestamps[0]) maxTS := float64(timestamps[len(timestamps)-1]) if minTS >= maxTS { maxTS = minTS + 60000.0 // Default 1-minute window } var pathBuilder strings.Builder firstX := paddingLeft lastX := paddingLeft + plotW for i := range timestamps { x := paddingLeft + ((float64(timestamps[i])-minTS)/(maxTS-minTS))*plotW y := paddingTop + plotH - ((values[i]-minVal)/(maxVal-minVal))*plotH if i == 0 { firstX = x fmt.Fprintf(&pathBuilder, "M %.2f,%.2f", x, y) } else { fmt.Fprintf(&pathBuilder, " L %.2f,%.2f", x, y) } if i == len(timestamps)-1 { lastX = x } } // Area gradient fill under the line areaPath := fmt.Sprintf("%s L %.2f,%.2f L %.2f,%.2f Z", pathBuilder.String(), lastX, paddingTop+plotH, firstX, paddingTop+plotH) // Time axis (X-axis) formatting and ticks span := time.Duration(int64(maxTS-minTS)) * time.Millisecond minTime := time.UnixMilli(int64(minTS)).UTC() maxTime := time.UnixMilli(int64(maxTS)).UTC() multiYear := minTime.Year() != maxTime.Year() || span > 180*24*time.Hour type tickLabel struct { line1 string line2 string } getTickLabel := func(t time.Time) tickLabel { switch { case span <= 10*time.Minute: dateFmt := "Jan 02" if multiYear { dateFmt = "Jan 02 '06" } return tickLabel{ line1: t.Format("15:04:05"), line2: t.Format(dateFmt), } case span <= 7*24*time.Hour: dateFmt := "Jan 02" if multiYear { dateFmt = "Jan 02 '06" } return tickLabel{ line1: t.Format("15:04"), line2: t.Format(dateFmt), } default: // > 7 days (e.g. 30 days, 90 days, 1 year) return tickLabel{ line1: t.Format("Jan 02"), line2: t.Format("2006"), } } } numTicks := 5 if width < 500 { numTicks = 3 } var xTicks strings.Builder for k := range numTicks { frac := float64(k) / float64(numTicks-1) x := paddingLeft + frac*plotW tMillis := int64(minTS + frac*(maxTS-minTS)) tVal := time.UnixMilli(tMillis).UTC() lbl := getTickLabel(tVal) var anchor string switch k { case 0: anchor = "start" case numTicks - 1: anchor = "end" default: anchor = "middle" } // Vertical subtle grid line if k > 0 && k < numTicks-1 { fmt.Fprintf(&xTicks, ``+"\n ", x, paddingTop, x, paddingTop+plotH, th.gridColor) } // Bottom tick mark fmt.Fprintf(&xTicks, ``+"\n ", x, paddingTop+plotH, x, paddingTop+plotH+4, th.tickColor) // X-axis time & date label (two-line) fmt.Fprintf(&xTicks, `%s%s`+"\n ", x, paddingTop+plotH+16, th.labelColor, th.monoFontFamily, anchor, x, lbl.line1, x, th.sublabelColor, lbl.line2) } latestVal := values[len(values)-1] midVal := (minVal + maxVal) / 2.0 _, err := fmt.Fprintf(w, ` %s Latest: %.2f %.2f %.2f %.2f %s UTC `, width, height, width, height, th.areaColor, th.areaOpacity, th.areaColor, rectAttr, th.titleColor, th.fontFamily, title, float64(width)-paddingRight, th.latestColor, th.monoFontFamily, latestVal, paddingLeft, paddingTop, paddingLeft+plotW, paddingTop, th.gridColor, paddingLeft-8, paddingTop+4, th.labelColor, th.monoFontFamily, maxVal, paddingLeft, paddingTop+plotH/2, paddingLeft+plotW, paddingTop+plotH/2, th.gridColor, paddingLeft-8, paddingTop+plotH/2+4, th.sublabelColor, th.monoFontFamily, midVal, paddingLeft, paddingTop+plotH, paddingLeft+plotW, paddingTop+plotH, th.axisColor, paddingLeft-8, paddingTop+plotH+4, th.labelColor, th.monoFontFamily, minVal, xTicks.String(), paddingLeft-8, paddingTop+plotH+16, th.sublabelColor, th.monoFontFamily, areaPath, pathBuilder.String(), th.lineColor, ) return err } var sparkBlocks = []rune{' ', '▂', '▃', '▄', '▅', '▆', '▇', '█'} // RenderASCII writes a concise statistical summary and ASCII sparkline // designed for LLMs, automated agents, and CLI output. func RenderASCII(w io.Writer, title string, timestamps []int64, values []float64) error { if len(values) == 0 { _, err := fmt.Fprintf(w, "Series: %s\nNo data in selected time range.\n", title) return err } minVal := values[0] maxVal := values[0] sum := 0.0 sortedVals := make([]float64, len(values)) copy(sortedVals, values) sort.Float64s(sortedVals) for _, v := range values { if v < minVal { minVal = v } if v > maxVal { maxVal = v } sum += v } mean := sum / float64(len(values)) p95Idx := max(int(math.Ceil(0.95*float64(len(sortedVals))))-1, 0) p95 := sortedVals[p95Idx] latest := values[len(values)-1] // Compute sparkline characters valRange := maxVal - minVal var spark strings.Builder for _, v := range values { var idx int if valRange == 0 { idx = 0 } else { idx = int(((v - minVal) / valRange) * float64(len(sparkBlocks)-1)) } if idx < 0 { idx = 0 } if idx >= len(sparkBlocks) { idx = len(sparkBlocks) - 1 } spark.WriteRune(sparkBlocks[idx]) } fromTime := time.UnixMilli(timestamps[0]).UTC().Format(time.RFC3339) toTime := time.UnixMilli(timestamps[len(timestamps)-1]).UTC().Format(time.RFC3339) _, err := fmt.Fprintf(w, "Series: %s\n"+ "Range: %s to %s (%d points)\n"+ "Metrics: Min: %.2f | Max: %.2f | Mean: %.2f | P95: %.2f | Latest: %.2f\n"+ "Trend: [%s]\n", title, fromTime, toTime, len(values), minVal, maxVal, mean, p95, latest, spark.String(), ) return err }