/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

var (
	uppercase bool
	lowercase bool
	titlecase bool
	wordcount bool
	charcount bool
)

var rootCmd = &cobra.Command{
	Use:   "mytextfmt [text]",
	Short: "A simple text formatter",
	Long: `mytextfmt is a CLI tool for formatting and analyzing text.

You can provide text as arguments or pipe it in via stdin.
Multiple formatting options can be applied simultaneously`,
	Args: cobra.ArbitraryArgs,
	Run:  runTextFormatter,
}

func init() {
	rootCmd.Flags().BoolVarP(&uppercase, "upper", "u", false, "Convert text to uppercase")
	rootCmd.Flags().BoolVarP(&lowercase, "lower", "l", false, "Convert text to lowercase")
	rootCmd.Flags().BoolVarP(&titlecase, "title", "t", false, "Convert text to titlecase")
	rootCmd.Flags().BoolVar(&wordcount, "words", false, "Count words in text")
	rootCmd.Flags().BoolVar(&charcount, "chars", false, "Count characters in text")
}

func runTextFormatter(cmd *cobra.Command, args []string) {
	var text string

	// Get input text from args or stdin
	if len(args) > 0 {
		text = strings.Join(args, " ")
	} else {
		scanner := bufio.NewScanner(os.Stdin)
		var lines []string

		for scanner.Scan() {
			lines = append(lines, scanner.Text())
		}

		text = strings.Join(lines, "\n")
	}

	if text == "" {
		fmt.Println("No input text was provided")

		return
	}

	result := text

	if uppercase {
		result = strings.ToUpper(result)
	}

	if lowercase {
		result = strings.ToLower(result)
	}

	if titlecase {
		result = strings.Title(result)
	}

	fmt.Println(result)

	if wordcount {
		words := len(strings.Fields(text))

		fmt.Printf("Word count [%d]\n", words)
	}

	if charcount {
		chars := len(text)

		fmt.Printf("Character count [%d]\n", chars)
	}
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
