package renderer

import (
	"testing"

	"gitea.dockr.co/kev/go-jdenticon/internal/engine"
)

// Benchmark optimized renderer to compare against baseline (958,401 B/op)
func BenchmarkOptimizedVsBaseline(b *testing.B) {
	b.Run("Optimized_64px_PNG", func(b *testing.B) {
		b.ResetTimer()
		b.ReportAllocs()

		for i := 0; i < b.N; i++ {
			// Use optimized renderer with typical identicon pattern
			renderer := NewPNGRenderer(64)

			// Simulate typical identicon generation (simplified)
			renderer.SetBackground("#f0f0f0", 1.0)

			// Add representative shapes (based on typical identicon output)
			renderer.BeginShape("#ff6b6b")
			renderer.AddPolygon([]engine.Point{{X: 0.2, Y: 0.2}, {X: 0.8, Y: 0.2}, {X: 0.5, Y: 0.8}})
			renderer.EndShape()

			renderer.BeginShape("#4ecdc4")
			renderer.AddPolygon([]engine.Point{{X: 0, Y: 0}, {X: 0.4, Y: 0}, {X: 0.4, Y: 0.4}, {X: 0, Y: 0.4}})
			renderer.EndShape()

			renderer.BeginShape("#45b7d1")
			renderer.AddCircle(engine.Point{X: 0.6, Y: 0.6}, 0.3, false)
			renderer.EndShape()

			_, err := renderer.ToPNG()
			if err != nil {
				b.Fatalf("Optimized PNG generation failed: %v", err)
			}
		}
	})
}

// Simulate the icon generation process for testing
// This creates a simple identicon structure for benchmarking
func BenchmarkOptimizedSimulatedGeneration(b *testing.B) {
	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {
		renderer := NewPNGRenderer(64)

		// Simulate typical identicon generation
		renderer.SetBackground("#f0f0f0", 1.0)

		// Add typical identicon shapes (3-5 shapes)
		shapes := []struct {
			color  string
			points []engine.Point
		}{
			{"#ff6b6b", []engine.Point{{X: 0.2, Y: 0.2}, {X: 0.8, Y: 0.2}, {X: 0.5, Y: 0.8}}},
			{"#4ecdc4", []engine.Point{{X: 0, Y: 0}, {X: 0.4, Y: 0}, {X: 0.4, Y: 0.4}, {X: 0, Y: 0.4}}},
			{"#45b7d1", []engine.Point{{X: 0.6, Y: 0.6}, {X: 1, Y: 0.6}, {X: 1, Y: 1}, {X: 0.6, Y: 1}}},
		}

		for _, shape := range shapes {
			renderer.BeginShape(shape.color)
			renderer.AddPolygon(shape.points)
			renderer.EndShape()
		}

		_, err := renderer.ToPNG()
		if err != nil {
			b.Fatalf("Simulated generation failed: %v", err)
		}
	}
}

// Direct memory comparison test - minimal overhead
func BenchmarkOptimizedPureMemory(b *testing.B) {
	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {
		// Create renderer - this is where the major memory allocation difference should be
		renderer := NewPNGRenderer(64)

		// Minimal shape to trigger rendering pipeline
		renderer.SetBackground("#ffffff", 1.0)
		renderer.BeginShape("#ff0000")
		renderer.AddPolygon([]engine.Point{{X: 0, Y: 0}, {X: 1, Y: 0}, {X: 0.5, Y: 1}})
		renderer.EndShape()

		_, err := renderer.ToPNG()
		if err != nil {
			b.Fatalf("Pure memory test failed: %v", err)
		}
	}
}
