package prompt

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

//go:embed templates/*.md
var defaultTemplates embed.FS

// Engine 提示词模板引擎，支持变量替换
type Engine struct {
	templates map[string]string // name -> template content
}

// New 从内嵌默认模板创建引擎
func New() *Engine {
	e := &Engine{templates: make(map[string]string)}
	entries, _ := defaultTemplates.ReadDir("templates")
	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		name := strings.TrimSuffix(entry.Name(), ".md")
		data, _ := defaultTemplates.ReadFile("templates/" + entry.Name())
		e.templates[name] = string(data)
	}
	return e
}

// LoadOverrides 从外部目录加载模板覆盖默认值
func (e *Engine) LoadOverrides(dir string) {
	entries, err := os.ReadDir(dir)
	if err != nil {
		return
	}
	for _, entry := range entries {
		if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
			continue
		}
		name := strings.TrimSuffix(entry.Name(), ".md")
		data, err := os.ReadFile(filepath.Join(dir, entry.Name()))
		if err == nil {
			e.templates[name] = string(data)
		}
	}
}

// Render 渲染模板，用 vars 替换 {{.Key}} 占位符
func (e *Engine) Render(name string, vars map[string]string) string {
	tmpl, ok := e.templates[name]
	if !ok {
		return ""
	}
	result := tmpl
	for k, v := range vars {
		result = strings.ReplaceAll(result, "{{."+k+"}}", v)
	}
	return result
}

// R 简写渲染，无变量
func (e *Engine) R(name string) string {
	return e.Render(name, nil)
}

// Has 检查模板是否存在
func (e *Engine) Has(name string) bool {
	_, ok := e.templates[name]
	return ok
}
