package sample

import (
	"bufio"
	"encoding/binary"
	"encoding/csv"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"sort"
	"strings"
	"sync"
	"time"
)

func FindSubstring(s string) bool {
	return strings.Index(s, "needle") != -1
}

func SingleCharConvert(b []byte) bool {
	return string(b) == "x"
}

func BuildPath(dir string, file string) string {
	return dir + "/" + file
}

func IntToString(n int) string {
	return fmt.Sprintf("%d", n)
}

func ConcatStrings(a, b, c string) string {
	return fmt.Sprintf("%s:%s:%s", a, b, c)
}

func ReplaceSingleChar(s string) string {
	return strings.ReplaceAll(s, "x", "y")
}

func NormalizeChained(s string) string {
	return strings.TrimSpace(strings.ToLower(strings.TrimPrefix(s, "pre")))
}

func WrapError(err error) error {
	return fmt.Errorf("failed: %s", err.Error())
}

func CutPrefixManual(s, prefix string) string {
	if strings.HasPrefix(s, prefix) {
		s = strings.TrimPrefix(s, prefix)
	}
	return s
}

func CutSuffixManual(s, suffix string) string {
	if strings.HasSuffix(s, suffix) {
		s = strings.TrimSuffix(s, suffix)
	}
	return s
}

func BuilderConcat(builder *strings.Builder, a, b string) {
	builder.WriteString(a + b)
}

func DeleteMapLoop(m map[string]int) {
	for k := range m {
		delete(m, k)
	}
}

func SortWithAdapter(items []string) {
	sort.Sort(sort.StringSlice(items))
}

func IterateByIndex(s string) {
	for i := 0; i < len(s); i++ {
		_ = s[i]
	}
}

func DoubleLookup(m map[string]int, k string) int {
	if _, ok := m[k]; ok {
		v := m[k]
		return v
	}
	return 0
}

func UseInterfaceSlice() {
	items := make([]interface{}, 0, 10)
	_ = items
}

func RangeStructItems(items []struct{ Name string; Age int; Bio string; Address string; Phone string }) {
	for _, v := range items {
		_ = v
	}
}

func MutexCounter(mu *sync.Mutex, count *int) {
	mu.Lock()
	*count++
	mu.Unlock()
}

func TimeNowLoop(items []string) {
	for _, item := range items {
		t := time.Now()
		_ = t
		_ = item
	}
}

func DeferLoop(items []string) {
	for _, item := range items {
		defer fmt.Println(item)
	}
}

func SelectSingle(ch chan int) int {
	select {
	case v := <-ch:
		return v
	}
}

func SyncGoroutine() int {
	ch := make(chan int, 1)
	go func() {
		ch <- 42
	}()
	return <-ch
}

func WaitGroupLoop(items []string) {
	var wg sync.WaitGroup
	for _, item := range items {
		wg.Add(1)
		go func(s string) {
			defer wg.Done()
			_ = s
		}(item)
	}
	wg.Wait()
}

func DeprecatedReadAll(r io.Reader) []byte {
	data, _ := ioutil.ReadAll(r)
	return data
}

func MarshalThenWrite(w http.ResponseWriter, v interface{}) {
	data, _ := json.Marshal(v)
	w.Write(data)
}

func CsvNoReuse(r io.Reader) {
	reader := csv.NewReader(r)
	for {
		_, err := reader.Read()
		if err != nil {
			break
		}
	}
}

func ReadBodyNoLimit(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	_ = body
	_ = w
}

func UncheckedAssertion(i interface{}) string {
	v := i.(string)
	return v
}

func RepeatedAssertions(i interface{}) {
	if _, ok := i.(string); ok {
		return
	}
	if _, ok := i.(int); ok {
		return
	}
	if _, ok := i.(bool); ok {
		return
	}
}

func RepeatErrorsNew() error {
	_ = errors.New("first error")
	_ = errors.New("second error")
	return errors.New("third error")
}

func NoWrapVerb(err error) error {
	return fmt.Errorf("context: %v", err)
}

func CompareErrorString(err error) bool {
	return err.Error() == "not found"
}

func PanicOnBadInput(v string) {
	panic("invalid input: " + v)
}

func UseOsGetenv(w http.ResponseWriter, r *http.Request) {
	key := os.Getenv("API_KEY")
	_ = key
	_ = w
}

func LenEmptyCheck(s string) bool {
	return len(s) == 0
}

func CloneWithAppend(src []int) []int {
	dst := append([]int(nil), src...)
	return dst
}

func SliceGrowNoCap(items []string) []string {
	var result []string
	for _, item := range items {
		result = append(result, item)
	}
	return result
}

func GroupWithoutPrealloc(values []int) map[string][]int {
	groups := map[string][]int{}
	for _, v := range values {
		key := fmt.Sprintf("%d", v%2)
		groups[key] = append(groups[key], v)
	}
	return groups
}

func ReadonlyClone(src []int) int {
	copyItems := append([]int(nil), src...)
	return len(copyItems)
}

func AppendToSubslice(original []int) []int {
	sub := original[1:3]
	sub = append(sub, 9)
	return sub
}

func DenseIntSet(limit int) map[int]bool {
	seen := make(map[int]bool)
	for i := 0; i < limit; i++ {
		seen[i] = true
	}
	return seen
}

func ReadConfigLocked(mu *sync.RWMutex, config struct{ Name string }) string {
	mu.RLock()
	value := config.Name
	mu.RUnlock()
	return value
}

func AllocateScratchBuffers(items []string) {
	for range items {
		buf := make([]byte, 4096)
		_ = buf
	}
}

type LockedCounter struct {
	mu    sync.Mutex
	count int
}

func (c LockedCounter) Increment() {
	c.mu.Lock()
	c.count++
	c.mu.Unlock()
}

func KnownProducerChannel(items []int) int {
	ch := make(chan int)
	for _, item := range items {
		ch <- item
	}
	return <-ch
}

func BinaryReadField(r io.Reader, order binary.ByteOrder) uint32 {
	var value uint32
	binary.Read(r, order, &value)
	return value
}

func DecodeDynamicNumbers(data []byte) map[string]any {
	var payload map[string]any
	json.Unmarshal(data, &payload)
	return payload
}

func ParseTrustedFeed(data string) {
	decoder := xml.NewDecoder(strings.NewReader(data))
	_ = decoder
}

func ScanLargeLogLines(r io.Reader) {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		_ = scanner.Text()
	}
}

func ExportedAnyValue(v any) {
	_ = v
}
