package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gitea.dockr.co/kev/go-jdenticon/jdenticon"
)

const (
	// generatorCacheSize defines the number of icons to cache in memory for performance.
	generatorCacheSize = 100
)

var (
	// Version information - injected at build time via ldflags

	// Version is the version string for the jdenticon CLI tool
	Version = "dev"

	// Commit is the git commit hash for the jdenticon CLI build
	Commit = "unknown"

	// BuildDate is the timestamp when the jdenticon CLI was built
	BuildDate = "unknown"

	cfgFile string
)

// getVersionString returns formatted version information
func getVersionString() string {
	version := fmt.Sprintf("jdenticon version %s\n", Version)

	if Commit != "unknown" && BuildDate != "unknown" {
		version += fmt.Sprintf("Built from commit %s on %s\n", Commit, BuildDate)
	} else if Commit != "unknown" {
		version += fmt.Sprintf("Built from commit %s\n", Commit)
	} else if BuildDate != "unknown" {
		version += fmt.Sprintf("Built on %s\n", BuildDate)
	}

	return version
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "jdenticon",
	Short: "Generate identicons from any input string",
	Long: `jdenticon is a command-line tool for generating highly recognizable identicons -
geometric avatar images generated deterministically from any input string.

Generate consistent, beautiful identicons as PNG or SVG files with customizable
color themes, padding, and styling options.`,
	Version: Version,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Set custom version template to use our detailed version info
	rootCmd.SetVersionTemplate(getVersionString())

	// Config file flag
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.jdenticon.yaml)")

	// Basic flags shared across commands
	var formatFlag FormatFlag = FormatSVG // Default to SVG
	rootCmd.PersistentFlags().IntP("size", "s", 200, "Size of the identicon in pixels")
	rootCmd.PersistentFlags().VarP(&formatFlag, "format", "f", `Output format ("png" or "svg")`)
	rootCmd.PersistentFlags().Float64P("padding", "p", 0.08, "Padding as percentage of icon size (0.0-0.5)")

	// Color configuration flags
	rootCmd.PersistentFlags().Float64("color-saturation", 0.5, "Saturation for colored shapes (0.0-1.0)")
	rootCmd.PersistentFlags().Float64("grayscale-saturation", 0.0, "Saturation for grayscale shapes (0.0-1.0)")
	rootCmd.PersistentFlags().String("bg-color", "", "Background color (hex format, e.g., #ffffff)")

	// Advanced configuration flags
	rootCmd.PersistentFlags().StringSlice("hue-restrictions", nil, "Restrict hues to specific degrees (0-360), e.g., --hue-restrictions=0,120,240")
	rootCmd.PersistentFlags().String("color-lightness", "0.4,0.8", "Color lightness range as min,max (0.0-1.0)")
	rootCmd.PersistentFlags().String("grayscale-lightness", "0.3,0.9", "Grayscale lightness range as min,max (0.0-1.0)")
	rootCmd.PersistentFlags().Int("png-supersampling", 8, "PNG supersampling factor (1-16)")

	// Bind flags to viper (errors are intentionally ignored as these bindings are non-critical)
	_ = viper.BindPFlag("size", rootCmd.PersistentFlags().Lookup("size"))
	_ = viper.BindPFlag("format", rootCmd.PersistentFlags().Lookup("format"))
	_ = viper.BindPFlag("padding", rootCmd.PersistentFlags().Lookup("padding"))
	_ = viper.BindPFlag("color-saturation", rootCmd.PersistentFlags().Lookup("color-saturation"))
	_ = viper.BindPFlag("grayscale-saturation", rootCmd.PersistentFlags().Lookup("grayscale-saturation"))
	_ = viper.BindPFlag("bg-color", rootCmd.PersistentFlags().Lookup("bg-color"))
	_ = viper.BindPFlag("hue-restrictions", rootCmd.PersistentFlags().Lookup("hue-restrictions"))
	_ = viper.BindPFlag("color-lightness", rootCmd.PersistentFlags().Lookup("color-lightness"))
	_ = viper.BindPFlag("grayscale-lightness", rootCmd.PersistentFlags().Lookup("grayscale-lightness"))
	_ = viper.BindPFlag("png-supersampling", rootCmd.PersistentFlags().Lookup("png-supersampling"))

	// Register format flag completion
	_ = rootCmd.RegisterFlagCompletionFunc("format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return []string{"png", "svg"}, cobra.ShellCompDirectiveNoFileComp
	})
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := os.UserHomeDir()
		cobra.CheckErr(err)

		// Search config in home directory with name ".jdenticon" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigType("yaml")
		viper.SetConfigName(".jdenticon")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		// Only ignore the error if the config file doesn't exist.
		// All other errors (e.g., permission denied, malformed file) should be noted.
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			fmt.Fprintln(os.Stderr, "Error reading config file:", err)
		}
	} else {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}

// populateConfigFromFlags creates a jdenticon.Config from viper settings and validates it
func populateConfigFromFlags() (jdenticon.Config, int, error) {
	config := jdenticon.DefaultConfig()

	// Get size from viper
	size := viper.GetInt("size")
	if size <= 0 {
		return config, 0, fmt.Errorf("size must be positive, got %d", size)
	}

	// Basic configuration
	config.Padding = viper.GetFloat64("padding")
	config.ColorSaturation = viper.GetFloat64("color-saturation")
	config.GrayscaleSaturation = viper.GetFloat64("grayscale-saturation")
	config.BackgroundColor = viper.GetString("bg-color")
	config.PNGSupersampling = viper.GetInt("png-supersampling")

	// Handle hue restrictions
	hueRestrictions := viper.GetStringSlice("hue-restrictions")
	if len(hueRestrictions) > 0 {
		hues := make([]float64, len(hueRestrictions))
		for i, hueStr := range hueRestrictions {
			var hue float64
			if _, err := fmt.Sscanf(hueStr, "%f", &hue); err != nil {
				return config, 0, fmt.Errorf("invalid hue restriction %q: %w", hueStr, err)
			}
			hues[i] = hue
		}
		config.HueRestrictions = hues
	}

	// Handle lightness ranges
	if colorLightnessStr := viper.GetString("color-lightness"); colorLightnessStr != "" {
		parts := strings.Split(colorLightnessStr, ",")
		if len(parts) != 2 {
			return config, 0, fmt.Errorf("invalid color-lightness format: expected 'min,max', got %q", colorLightnessStr)
		}
		min, errMin := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
		max, errMax := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
		if errMin != nil || errMax != nil {
			return config, 0, fmt.Errorf("invalid color-lightness value: %w", errors.Join(errMin, errMax))
		}
		config.ColorLightnessRange = [2]float64{min, max}
	}

	if grayscaleLightnessStr := viper.GetString("grayscale-lightness"); grayscaleLightnessStr != "" {
		parts := strings.Split(grayscaleLightnessStr, ",")
		if len(parts) != 2 {
			return config, 0, fmt.Errorf("invalid grayscale-lightness format: expected 'min,max', got %q", grayscaleLightnessStr)
		}
		min, errMin := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
		max, errMax := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
		if errMin != nil || errMax != nil {
			return config, 0, fmt.Errorf("invalid grayscale-lightness value: %w", errors.Join(errMin, errMax))
		}
		config.GrayscaleLightnessRange = [2]float64{min, max}
	}

	// Validate configuration
	if err := config.Validate(); err != nil {
		return config, 0, fmt.Errorf("invalid configuration: %w", err)
	}

	return config, size, nil
}

// getFormatFromViper retrieves and validates the format from Viper configuration
func getFormatFromViper() (FormatFlag, error) {
	formatStr := viper.GetString("format")
	var format FormatFlag
	if err := format.Set(formatStr); err != nil {
		return FormatSVG, fmt.Errorf("invalid format in config: %w", err)
	}
	return format, nil
}

// renderIcon converts an icon to bytes based on the specified format
func renderIcon(icon *jdenticon.Icon, format FormatFlag) ([]byte, error) {
	switch format {
	case FormatSVG:
		svgStr, err := icon.ToSVG()
		if err != nil {
			return nil, fmt.Errorf("failed to generate SVG: %w", err)
		}
		return []byte(svgStr), nil
	case FormatPNG:
		pngBytes, err := icon.ToPNG()
		if err != nil {
			return nil, fmt.Errorf("failed to generate PNG: %w", err)
		}
		return pngBytes, nil
	default:
		return nil, fmt.Errorf("unsupported format: %s", format)
	}
}
