package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	// Used for flags.
	inputFile  string
	separators string
	hashType   string
	targetHash string
	verbose    bool
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "hashcrafter [target_hash]",
	Short: "A powerful hash cracking tool that generates all possible combinations of text strings",
	Long: `HashCrafter is a command-line tool that generates all possible combinations 
of text strings from an input file and tests them against a specified hash.

It reads strings from a text file (one per line), generates all possible permutations 
with specified separators, hashes them, and checks for matches.

Example:
  hashcrafter -i list.txt -s " ,|,-,_" -t sha256 65496d766ab94b84acbd9609de3b61bbe90407e864f5212613b52c0207af291d`,
	Args: cobra.ExactArgs(1),
	RunE: runHashCraft,
}

// Execute adds all child commands to the root command and sets flags appropriately.
func Execute() error {
	return rootCmd.Execute()
}

func init() {
	// Here you will define your flags and configuration settings.
	rootCmd.Flags().StringVarP(&inputFile, "input", "i", "", "Input file containing strings (one per line) (required)")
	rootCmd.Flags().StringVarP(&separators, "separators", "s", ", ,|,-,_,.,/,:,;,+,&,~", "Comma-separated list of separators to use between strings")
	rootCmd.Flags().StringVarP(&hashType, "type", "t", "sha256", "Hash type to use (md5, sha1, sha224, sha256, sha384, sha512, sha3-224, sha3-256, sha3-384, sha3-512, blake2b-256, blake2b-384, blake2b-512)")
	rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose output")

	// Mark required flags
	rootCmd.MarkFlagRequired("input")

	rootCmd.AddCommand(versionCmd)
}

func runHashCraft(cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("target hash is required")
	}

	targetHash = args[0]

	// Validate hash type
	validHashTypes := map[string]bool{
		"md5":         true,
		"sha1":        true,
		"sha224":      true,
		"sha256":      true,
		"sha384":      true,
		"sha512":      true,
		"sha3-224":    true,
		"sha3-256":    true,
		"sha3-384":    true,
		"sha3-512":    true,
		"blake2b-256": true,
		"blake2b-384": true,
		"blake2b-512": true,
	}

	if !validHashTypes[hashType] {
		return fmt.Errorf("invalid hash type: %s. Supported types: md5, sha1, sha256, sha512", hashType)
	}

	// Check if input file exists
	if _, err := os.Stat(inputFile); os.IsNotExist(err) {
		return fmt.Errorf("input file does not exist: %s", inputFile)
	}

	return processHashCraft()
}
