package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/kevin/go-jdenticon/jdenticon"
)

func main() {
	var (
		value  = flag.String("value", "", "Input value to generate identicon for (required)")
		size   = flag.Int("size", 200, "Size of the identicon in pixels")
		format = flag.String("format", "svg", "Output format: svg or png")
		output = flag.String("output", "", "Output file (if empty, prints to stdout)")
	)
	flag.Parse()

	if *value == "" {
		fmt.Fprintf(os.Stderr, "Error: -value is required\n")
		flag.Usage()
		os.Exit(1)
	}

	icon, err := jdenticon.Generate(*value, *size)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error generating identicon: %v\n", err)
		os.Exit(1)
	}

	var result []byte
	switch *format {
	case "svg":
		svgStr, err := icon.ToSVG()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error generating SVG: %v\n", err)
			os.Exit(1)
		}
		result = []byte(svgStr)
	case "png":
		pngBytes, err := icon.ToPNG()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error generating PNG: %v\n", err)
			os.Exit(1)
		}
		result = pngBytes
	default:
		fmt.Fprintf(os.Stderr, "Error: invalid format %s (use svg or png)\n", *format)
		os.Exit(1)
	}

	if *output != "" {
		if err := os.WriteFile(*output, result, 0644); err != nil {
			fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Identicon saved to %s\n", *output)
	} else {
		fmt.Print(string(result))
	}
}