// main.go — Demonstrates core Go features for Doom Emacs workflow.
//
// Navigate: C-M-a/e (function boundaries), SPC s i (imenu), gd (definition)
// Format:   SPC m f (goimports), Run: SPC m r, Test: SPC m t, Build: SPC m b
package main

import (
	"fmt"
	"strings"
	"sync"
	"time"
)

// Task represents a work item with priority.
type Task struct {
	Title    string
	Priority int
	Done     bool
}

// Summary returns a human-readable one-line description.
func (t *Task) Summary() string {
	status := "TODO"
	if t.Done {
		status = "DONE"
	}
	return fmt.Sprintf("[%s] %s (p%d)", status, t.Title, t.Priority)
}

// MarkDone marks the task as completed.
func (t *Task) MarkDone() {
	t.Done = true
}

// filterByPriority returns undone tasks with priority >= minPriority.
func filterByPriority(tasks []*Task, minPriority int) []*Task {
	var result []*Task
	for _, t := range tasks {
		if !t.Done && t.Priority >= minPriority {
			result = append(result, t)
		}
	}
	return result
}

// countWords demonstrates a goroutine + channel pattern.
// It counts words in each input string concurrently.
func countWords(inputs []string) map[string]int {
	type result struct {
		input string
		count int
	}

	ch := make(chan result, len(inputs))
	var wg sync.WaitGroup

	for _, s := range inputs {
		wg.Add(1)
		go func(text string) {
			defer wg.Done()
			// Simulate work
			time.Sleep(10 * time.Millisecond)
			ch <- result{input: text, count: len(strings.Fields(text))}
		}(s)
	}

	// Close channel after all goroutines finish
	go func() {
		wg.Wait()
		close(ch)
	}()

	counts := make(map[string]int)
	for r := range ch {
		counts[r.input] = r.count
	}
	return counts
}

func main() {
	tasks := []*Task{
		{Title: "Write tests", Priority: 2},
		{Title: "Update docs", Priority: 1},
		{Title: "Deploy v2", Priority: 2},
	}

	tasks[0].MarkDone()

	fmt.Println("Open tasks (priority >= 2):")
	for _, t := range filterByPriority(tasks, 2) {
		fmt.Println(" ", t.Summary())
	}

	// Goroutine demo
	sentences := []string{
		"Go is a compiled language",
		"Goroutines are lightweight threads",
		"Channels enable safe communication",
	}
	counts := countWords(sentences)
	fmt.Println("\nWord counts:")
	for s, c := range counts {
		fmt.Printf("  %q → %d words\n", s, c)
	}
}
