package cmd

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"

	"skraak/utils"
)

// RunXXHash handles the "xxhash" subcommand
func RunXXHash(args []string) {
	fs := flag.NewFlagSet("xxhash", flag.ExitOnError)
	filePath := fs.String("file", "", "Path to file (required)")

	fs.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: skraak xxhash --file <path>\n\n")
		fmt.Fprintf(os.Stderr, "Compute XXH64 hash of a file (same format stored in database).\n\n")
		fmt.Fprintf(os.Stderr, "Options:\n")
		fs.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\nExamples:\n")
		fmt.Fprintf(os.Stderr, "  skraak xxhash --file recording.wav\n")
		fmt.Fprintf(os.Stderr, "  skraak xxhash --file /path/to/audio.wav | jq '.hash'\n")
	}

	if err := fs.Parse(args); err != nil {
		os.Exit(1)
	}

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

	// Compute hash
	hash, err := utils.ComputeXXH64(*filePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}

	// Output as JSON
	output := map[string]string{
		"file": *filePath,
		"hash": hash,
	}

	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(output)
}