package shell

import (
	"bufio"
	"os"
	"path/filepath"
	"strings"
)

// ExtractScriptDescription parses a script file and returns the first
// meaningful comment line as a description. Skips shebangs and empty lines.
// Falls back to the filename (without extension, underscores replaced by spaces).
func ExtractScriptDescription(scriptPath string) string {
	file, err := os.Open(scriptPath)
	if err != nil {
		return fallbackDescription(scriptPath)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	lineCount := 0
	for scanner.Scan() && lineCount < 5 {
		line := strings.TrimSpace(scanner.Text())
		lineCount++

		if strings.HasPrefix(line, "#!") || line == "" {
			continue
		}
		if strings.HasPrefix(line, "#") {
			desc := strings.TrimSpace(strings.TrimPrefix(line, "#"))
			desc = strings.TrimSpace(strings.TrimPrefix(desc, "Script:"))
			desc = strings.TrimSpace(strings.TrimPrefix(desc, "Script para"))
			desc = strings.TrimSpace(strings.TrimPrefix(desc, "Descripción:"))
			desc = strings.TrimSpace(strings.TrimPrefix(desc, "Description:"))
			if desc != "" {
				return desc
			}
		}
	}

	return fallbackDescription(scriptPath)
}

func fallbackDescription(scriptPath string) string {
	name := filepath.Base(scriptPath)
	name = strings.TrimSuffix(name, filepath.Ext(name))
	return strings.ReplaceAll(name, "_", " ")
}
