package cmd

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

	"skraak/utils"
)

// RunXXHash handles the "xxhash" subcommand
//
// JSON output schema:
//
//	{
//	  "file": string,  // Path to the hashed file
//	  "hash": string   // XXH64 hash (hex string)
//	}
func RunXXHash(args []string) error {
	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 {
		return fmt.Errorf("parsing flags: %w", err)
	}

	if *filePath == "" {
		fs.Usage()
		return fmt.Errorf("--file is required")
	}

	hash, err := utils.ComputeXXH64(*filePath)
	if err != nil {
		return fmt.Errorf("computing hash: %w", err)
	}

	output := map[string]string{
		"file": *filePath,
		"hash": hash,
	}

	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	if err := enc.Encode(output); err != nil {
		return fmt.Errorf("encoding output: %w", err)
	}
	return nil
}