package sample

import (
	"bufio"
	"encoding/binary"
	"encoding/csv"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net/http"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

func ContainsCheck(s string) bool {
	return strings.Contains(s, "needle")
}

func DirectByteCheck(s string) bool {
	return s[0] == 'x'
}

func JoinPath(dir string, file string) string {
	return filepath.Join(dir, file)
}

func ItoaConvert(n int) string {
	return strconv.Itoa(n)
}

func SimpleConcat(a, b string) string {
	return a + ":" + b
}

func CutPrefixClean(s, prefix string) (string, bool) {
	return strings.CutPrefix(s, prefix)
}

func CutSuffixClean(s, suffix string) (string, bool) {
	return strings.CutSuffix(s, suffix)
}

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

func NewMap() map[string]int {
	return make(map[string]int)
}

func SortDirect(items []string) {
	sort.Strings(items)
}

func RangeRune(s string) {
	for _, r := range s {
		_ = r
	}
}

func SingleLookup(m map[string]int, k string) (int, bool) {
	v, ok := m[k]
	return v, ok
}

func TypedSlice() []int {
	return make([]int, 0, 10)
}

func AtomicCounter(count *int64) {
	atomic.AddInt64(count, 1)
}

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

func DeferOnce() {
	defer fmt.Println("done")
}

func DirectReceive(ch chan int) int {
	return <-ch
}

func DirectCall() int {
	return 42
}

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

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

func encoderDirect(w http.ResponseWriter, v map[string]string) {
	json.NewEncoder(w).Encode(v)
}

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

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

func safeAssertion(i interface{}) (string, bool) {
	v, ok := i.(string)
	return v, ok
}

func typeSwitch(i interface{}) {
	switch v := i.(type) {
	case string:
		_ = v
	case int:
		_ = v
	}
}

var ErrNotFound = errors.New("not found")

func UseSentinel() error {
	return ErrNotFound
}

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

func CompareWithIs(err error) bool {
	return errors.Is(err, ErrNotFound)
}

func ReturnError(v string) error {
	return fmt.Errorf("invalid input: %s", v)
}

func EmptyStringCheck(s string) bool {
	return s == ""
}

func CloneWithCopy(src []int) []int {
	dst := make([]int, len(src))
	copy(dst, src)
	return dst
}

func SliceWithCap(items []string) []string {
	result := make([]string, 0, len(items))
	for _, item := range items {
		result = append(result, item)
	}
	return result
}

func GroupWithPrealloc(values []int) map[string][]int {
	groups := map[string][]int{}
	for _, v := range values {
		key := strconv.Itoa(v % 2)
		bucket := groups[key]
		if bucket == nil {
			bucket = make([]int, 0, 4)
		}
		bucket = append(bucket, v)
		groups[key] = bucket
	}
	return groups
}

func UseClear(m map[string]int) {
	clear(m)
}

func CloneThenMutate(src []int) []int {
	copyItems := make([]int, len(src))
	copy(copyItems, src)
	copyItems[0] = 7
	return copyItems
}

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

func DenseSet(limit int) []bool {
	return make([]bool, limit)
}

type ConfigValue struct {
	Name string
}

func ReadConfigAtomic(holder *atomic.Value) string {
	cfgAny := holder.Load()
	cfg, ok := cfgAny.(ConfigValue)
	_ = ok
	return cfg.Name
}

func ReuseBuffers(items []string, pool *sync.Pool) {
	for range items {
		buf := pool.Get()
		_ = buf
		pool.Put(buf)
	}
}

type SafeCounter struct {
	mu    sync.Mutex
	count int
}

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

func BufferedChannel(items []int) chan int {
	ch := make(chan int, len(items))
	return ch
}

func BinaryUint(buf []byte) uint32 {
	return binary.BigEndian.Uint32(buf[:4])
}

func DecodeDynamicNumbersSafe(data string) map[string]any {
	var payload map[string]any
	decoder := json.NewDecoder(strings.NewReader(data))
	decoder.UseNumber()
	decoder.Decode(&payload)
	return payload
}

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

func ScanLargeLogLinesSafe(r io.Reader) {
	scanner := bufio.NewScanner(r)
	scanner.Buffer(make([]byte, 0, 128*1024), 128*1024)
	for scanner.Scan() {
		_ = scanner.Text()
	}
}

func ExportedConcreteValue(v string) {
	_ = v
}
