cmd/ez-agent-configurator/app.go

package main

import (
	"bytes"
	"fmt"
	"os"
	"regexp"
	"sort"
	"strings"

	"git.cafe/ezterry/ez-agent/pkg/oauth"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
	"gopkg.in/yaml.v3"
)

type modelCacheEntry struct {
	models   []DiscoveredModel
	source   string // optional external catalog provenance
	err      error
	identity string
	catalog  *subscriptionModelCatalog
}

type authEdit struct {
	apiKey, apiKeyEnv string
	remove            bool
}

type Layer string

const (
	LayerBuiltin Layer = "builtin"
	LayerUser    Layer = "user"
	LayerProject Layer = "project"
)

type viewEntry struct {
	name       string
	bread      string
	widget     tview.Primitive
	onFocus    func()
	escapeHook func()
	onClose    func()
	form       *formView
}

type formField struct {
	Label        string
	Value        string
	FieldWidth   int
	FieldHeight  int
	ReadOnly     bool
	Mask         bool
	Type         string // "text" (default), "textarea", "dropdown", "bool", "picklist", "toolpicklist"
	Options      []string
	Checked      bool
	OnChange     func(text string)
	PicklistDone func(selected []string)
	Selected     []string  // Exact tool selections, independent of Value's display text.
	Inherited    []string  // Tool choices available for restoring inheritance.
	Widget       focusable // Optional caller-owned editable widget.
}

type actionItem struct {
	Label  string
	Hint   string
	Action func()
}

type listItem struct {
	Label      string
	Header     bool // Leading guidance rendered separately with word wrapping.
	Selectable bool
	Color      string
	Action     func()
}

type ConfiguratorApp struct {
	app       *tview.Application
	layers    *Layers
	pages     *tview.Pages
	bottomBar *tview.TextView
	authUI    *authUIQueue

	viewStack    []viewEntry
	viewSequence uint64

	dirtyConfig bool
	dirtyAuth   bool

	authNode  *yaml.Node
	authPath  string
	authEdits map[string]authEdit
	cwd       string

	providerDefaults map[string]config.ProviderDefaults

	modelCache     map[string]modelCacheEntry
	remoteCatalogs map[string]remoteCatalogCache

	// Exact enabled subset before a grouped model was inactivated in this session.
	disabledModelPrograms map[modelProgramGroup]map[string]bool
}

const (
	viewStartup     = "startup"
	viewMainMenu    = "main-menu"
	viewProviders   = "providers"
	viewModes       = "modes"
	viewServiceList = "services"
	viewGlobals     = "globals"
	viewProvEdit    = "prov-edit"
	viewServiceEdit = "service-edit"
	viewModelList   = "model-list"
	viewModelEdit   = "model-edit"
	viewOverrides   = "overrides"
	viewOvEdit      = "ov-edit"
	viewConfirm     = "confirm"
	viewAddProv     = "add-prov"
	viewAddMode     = "add-mode"
	viewAddService  = "add-service"
	viewAddModel    = "add-model"
	viewAddOv       = "add-ov"
)

func NewConfiguratorApp(layers *Layers, authNode *yaml.Node, authPath string, cwd string) *ConfiguratorApp {
	a := &ConfiguratorApp{
		app:      tview.NewApplication(),
		layers:   layers,
		authNode: authNode,
		authPath: authPath,
		pages:    tview.NewPages(),
		authUI:   newAuthUIQueue(),
		cwd:      cwd,
	}

	a.bottomBar = tview.NewTextView().
		SetDynamicColors(true).
		SetWrap(false)
	a.bottomBar.SetBorderPadding(0, 0, 1, 0)

	root := tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(a.pages, 0, 1, true).
		AddItem(a.bottomBar, 1, 0, false)

	a.app.SetRoot(root, true)
	a.app.EnableMouse(true)
	a.app.EnablePaste(true)
	a.app.SetInputCapture(a.globalInput)
	a.app.SetBeforeDrawFunc(a.authBeforeDraw)

	a.pushView(viewStartup, "Config", a.buildStartupView(), nil)

	return a
}

func (a *ConfiguratorApp) globalInput(event *tcell.EventKey) *tcell.EventKey {
	if a.authUI != nil && event == a.authUI.wake {
		a.drainAuthUpdates()
		return nil
	}
	if event.Key() == tcell.KeyCtrlC {
		a.stop()
		return nil
	}
	if event.Key() == tcell.KeyEscape {
		if a.pages.HasPage("confirm-exit") {
			return event
		}
		if len(a.viewStack) > 0 {
			current := a.viewStack[len(a.viewStack)-1]
			if current.form != nil && current.form.hasOpenDropdown() {
				return event
			}
			if current.escapeHook != nil {
				current.escapeHook()
				return nil
			}
		}
		if len(a.viewStack) <= 1 {
			a.stop()
			return nil
		}
		current := a.viewStack[len(a.viewStack)-1]
		if strings.HasPrefix(current.name, viewStartup+"-") {
			a.stop()
			return nil
		}
		if strings.HasPrefix(current.name, viewMainMenu+"-") {
			if a.dirtyConfig || a.dirtyAuth {
				a.showConfirmExit()
				return nil
			}
			a.stop()
			return nil
		}
		a.popView()
		return nil
	}
	a.drainAuthUpdates()
	return event
}

func (a *ConfiguratorApp) pushView(name, bread string, widget tview.Primitive, onFocus func()) {
	a.viewSequence++
	pageName := fmt.Sprintf("%s-%d", name, a.viewSequence)
	a.viewStack = append(a.viewStack, viewEntry{name: pageName, bread: bread, widget: widget, onFocus: onFocus})
	a.pages.AddAndSwitchToPage(pageName, widget, true)
	a.app.SetFocus(widget)
	a.updateBottomBar()
}

func (a *ConfiguratorApp) setEscapeHook(hook func()) {
	if len(a.viewStack) > 0 {
		a.viewStack[len(a.viewStack)-1].escapeHook = hook
	}
}

func (a *ConfiguratorApp) popView() {
	if len(a.viewStack) <= 1 {
		a.stop()
		return
	}
	current := a.viewStack[len(a.viewStack)-1]
	if strings.HasPrefix(current.name, viewStartup+"-") {
		a.stop()
		return
	}
	if strings.HasPrefix(current.name, viewMainMenu+"-") {
		if a.dirtyConfig || a.dirtyAuth {
			a.showConfirmExit()
			return
		}
		a.stop()
		return
	}
	if current.onClose != nil {
		current.onClose()
	}
	a.pages.RemovePage(current.name)
	a.viewStack = a.viewStack[:len(a.viewStack)-1]
	prev := a.viewStack[len(a.viewStack)-1]
	if prev.onFocus != nil {
		prev.onFocus()
	}
	a.pages.SwitchToPage(prev.name)
	a.app.SetFocus(prev.widget)
	a.updateBottomBar()
}

func (a *ConfiguratorApp) popToView(targetPrefix string) {
	for i := len(a.viewStack) - 1; i >= 0; i-- {
		if strings.HasPrefix(a.viewStack[i].name, targetPrefix+"-") {
			for j := len(a.viewStack) - 1; j > i; j-- {
				if a.viewStack[j].onClose != nil {
					a.viewStack[j].onClose()
				}
				a.pages.RemovePage(a.viewStack[j].name)
			}
			a.viewStack = a.viewStack[:i+1]
			a.pages.SwitchToPage(a.viewStack[i].name)
			a.app.SetFocus(a.viewStack[i].widget)
			a.updateBottomBar()
			return
		}
	}
}

func (a *ConfiguratorApp) showConfirmExit() {
	modal := tview.NewModal().
		SetText("You have unsaved changes.\nExit without saving?").
		AddButtons([]string{"No", "Yes"}).
		SetDoneFunc(func(buttonIndex int, buttonLabel string) {
			a.pages.RemovePage("confirm-exit")
			if buttonLabel == "Yes" {
				a.stop()
				return
			}
			current := a.viewStack[len(a.viewStack)-1]
			a.app.SetFocus(current.widget)
		})

	centered := centerPrimitive(modal, 40, 10)
	a.pages.AddAndSwitchToPage("confirm-exit", centered, true)
	a.app.SetFocus(modal)
}

func (a *ConfiguratorApp) updateBottomBar() {
	var bread string
	for i, v := range a.viewStack {
		if i > 0 {
			bread += " > "
		}
		bread += v.bread
	}
	hint := "  ↑↓ navigate  Enter select  Esc back"
	a.bottomBar.SetText(fmt.Sprintf("[dim]%s[-:-:-][yellow]%s[-:-:-]", bread, hint))
}

func (a *ConfiguratorApp) setStatus(msg string) {
	var bread string
	for i, v := range a.viewStack {
		if i > 0 {
			bread += " > "
		}
		bread += v.bread
	}
	a.bottomBar.SetText(fmt.Sprintf("[dim]%s[-:-:-]  [yellow]%s[-:-:-]", bread, msg))
}

func (a *ConfiguratorApp) setStatusOK(msg string) {
	var bread string
	for i, v := range a.viewStack {
		if i > 0 {
			bread += " > "
		}
		bread += v.bread
	}
	a.bottomBar.SetText(fmt.Sprintf("[dim]%s[-:-:-]  [green]%s[-:-:-]", bread, msg))
}

func (a *ConfiguratorApp) setStatusErr(msg string) {
	var bread string
	for i, v := range a.viewStack {
		if i > 0 {
			bread += " > "
		}
		bread += v.bread
	}
	a.bottomBar.SetText(fmt.Sprintf("[dim]%s[-:-:-]  [red]%s[-:-:-]", bread, msg))
}

func (a *ConfiguratorApp) MarkDirtyConfig() {
	a.dirtyConfig = true
}

func (a *ConfiguratorApp) MarkDirtyAuth() {
	a.dirtyAuth = true
}

func (a *ConfiguratorApp) Run() error {
	defer a.shutdownAuth()
	return a.app.Run()
}

func (a *ConfiguratorApp) ApplyChanges() error {
	if a.dirtyConfig {
		editNode := a.layers.EditNode()
		editPath := a.layers.EditPath()
		if editNode != nil && editPath != "" {
			if err := writeYAMLNode(editNode, editPath); err != nil {
				return fmt.Errorf("writing config: %w", err)
			}
		}
		a.dirtyConfig = false
	}

	if a.dirtyAuth {
		if err := a.applyAuthEdits(); err != nil {
			return fmt.Errorf("writing auth: %w", err)
		}
		a.dirtyAuth = false
	}

	return nil
}

func layerColor(l Layer) string {
	switch l {
	case LayerBuiltin:
		return "maroon"
	case LayerProject:
		return "yellow"
	default:
		return "white"
	}
}

func layerTag(l Layer) string {
	switch l {
	case LayerBuiltin:
		return "[maroon][[]builtin][-:-:-]"
	case LayerProject:
		return "[yellow][[]project][-:-:-]"
	default:
		return "[white][[]yours][-:-:-]"
	}
}

func (a *ConfiguratorApp) getAllTools() []string {
	seen := make(map[string]bool)
	var out []string

	entries := getServiceEntries(a)
	for _, e := range entries {
		if e.Node != nil {
			if tools := getMapField(e.Node, "tools"); tools != nil && tools.Kind == yaml.SequenceNode {
				for _, t := range tools.Content {
					if t.Kind == yaml.ScalarNode && !seen[t.Value] {
						seen[t.Value] = true
						out = append(out, t.Value)
					}
				}
			}
		}
	}

	sort.Strings(out)
	return out
}

func (a *ConfiguratorApp) getAllPlugins() []string {
	seen := make(map[string]bool)
	var out []string

	entries := getServiceEntries(a)
	for _, e := range entries {
		if e.Node != nil {
			if plugins := getMapField(e.Node, "plugins"); plugins != nil && plugins.Kind == yaml.SequenceNode {
				for _, p := range plugins.Content {
					if p.Kind == yaml.ScalarNode && !seen[p.Value] {
						seen[p.Value] = true
						out = append(out, p.Value)
					}
				}
			}
		}
	}

	sort.Strings(out)
	return out
}

func (a *ConfiguratorApp) getAllMacros() []string {
	seen := make(map[string]bool)
	var out []string

	entries := getServiceEntries(a)
	for _, e := range entries {
		if e.Node != nil {
			if macros := getMapField(e.Node, "macros"); macros != nil && macros.Kind == yaml.SequenceNode {
				for _, m := range macros.Content {
					if m.Kind == yaml.ScalarNode && !seen[m.Value] {
						seen[m.Value] = true
						out = append(out, m.Value)
					}
				}
			}
		}
	}

	sort.Strings(out)
	return out
}

type ProviderInfo struct {
	Name       string
	Type       string
	BaseURL    string
	HasListing bool
	Models     []ModelInfo
	Layer      Layer
}

type ModelInfo struct {
	Name           string
	MaxContext     int
	MaxTokens      int
	ThinkingLevels []string
	ZDRSupported   *bool
	Active         bool
}

func (a *ConfiguratorApp) GetEffectiveProviders() []ProviderInfo {
	var out []ProviderInfo
	root := unwrapDoc(a.layers.EffectiveForEditTarget())
	if root == nil {
		return out
	}
	providers := getMapField(root, "providers")
	if providers == nil {
		return out
	}

	for i := 0; i < len(providers.Content)-1; i += 2 {
		name := providers.Content[i].Value
		pNode := providers.Content[i+1]

		if pNode.Kind == yaml.MappingNode {
			if rm := getMapField(pNode, "_removed"); rm != nil && rm.Value == "true" {
				continue
			}
		}

		info := ProviderInfo{Name: name}

		if t := getMapField(pNode, "type"); t != nil {
			info.Type = t.Value
		}
		if bu := getMapField(pNode, "base_url"); bu != nil {
			info.BaseURL = bu.Value
		}
		if hl := getMapField(pNode, "has_listing"); hl != nil {
			info.HasListing = hl.Value == "true"
		}

		if modelsSeq := getMapField(pNode, "models"); modelsSeq != nil && modelsSeq.Kind == yaml.SequenceNode {
			for _, mNode := range modelsSeq.Content {
				if mNode.Kind == yaml.MappingNode {
					me := ModelInfo{Active: true}
					if n := getMapField(mNode, "name"); n != nil {
						me.Name = n.Value
					}
					if mc := getMapField(mNode, "max_context"); mc != nil {
						fmt.Sscanf(mc.Value, "%d", &me.MaxContext)
					}
					if mt := getMapField(mNode, "max_tokens"); mt != nil {
						fmt.Sscanf(mt.Value, "%d", &me.MaxTokens)
					}
					if tl := getMapField(mNode, "thinking_levels"); tl != nil && tl.Kind == yaml.SequenceNode {
						me.ThinkingLevels = seqToStrings(tl)
					}
					if zs := getMapField(mNode, "zdr_supported"); zs != nil {
						val := zs.Value == "true"
						me.ZDRSupported = &val
					}
					info.Models = append(info.Models, me)
				}
			}
		}

		info.Layer = a.attributeProvider(name)
		out = append(out, info)
	}

	sort.Slice(out, func(i, j int) bool {
		return out[i].Name < out[j].Name
	})
	return out
}

func (a *ConfiguratorApp) attributeProvider(name string) Layer {
	if providerNodeOwns(a.layers.EditNode(), name) {
		return a.layers.EditTarget
	}
	if a.layers.EditTarget == LayerProject && providerNodeOwns(a.layers.UserNode, name) {
		return LayerUser
	}
	return LayerBuiltin
}

func providerNodeOwns(node *yaml.Node, name string) bool {
	p := getProviderNode(node, name)
	if p == nil {
		return false
	}
	if p.Kind == yaml.MappingNode {
		if rm := getMapField(p, "_removed"); rm != nil && rm.Value == "true" {
			return false
		}
	}
	return true
}

func getProviderNode(node *yaml.Node, name string) *yaml.Node {
	root := unwrapDoc(node)
	if root == nil {
		return nil
	}
	providers := getMapField(root, "providers")
	if providers == nil {
		return nil
	}
	return getMapField(providers, name)
}

func (a *ConfiguratorApp) getAuthKey(providerName string) string {
	key, _ := a.getAuthEntry(providerName)
	return key
}

// AuthEntryInfo holds the full auth state for a provider, including OAuth.
type AuthEntryInfo struct {
	APIKey      string
	APIKeyEnv   string
	IsOAuth     bool // subscription authentication, including reconnect-only legacy records
	IsLegacy    bool
	Credentials *oauth.OAuthCredentials
	Identity    string // Human display label, never a registration ID or token.
}

func (a *ConfiguratorApp) getAuthEntry(providerName string) (apiKey, apiKeyEnv string) {
	info := a.getAuthEntryFull(providerName)
	return info.APIKey, info.APIKeyEnv
}

func (a *ConfiguratorApp) getAuthEntryFull(providerName string) AuthEntryInfo {
	// Explicit unsaved API-key edits outrank any subscription-driven disk reload.
	if edit, ok := a.authEdits[providerName]; ok {
		if edit.remove {
			return AuthEntryInfo{}
		}
		return AuthEntryInfo{APIKey: edit.apiKey, APIKeyEnv: edit.apiKeyEnv}
	}
	if a.authNode == nil {
		return AuthEntryInfo{}
	}
	root := unwrapDoc(a.authNode)
	if root == nil || root.Kind != yaml.MappingNode {
		return AuthEntryInfo{}
	}
	providerAuth := getMapField(root, providerName)
	if providerAuth == nil {
		return AuthEntryInfo{}
	}
	info := AuthEntryInfo{}
	if ak := getMapField(providerAuth, "api_key"); ak != nil {
		info.APIKey = ak.Value
	}
	if ake := getMapField(providerAuth, "api_key_env"); ake != nil {
		info.APIKeyEnv = ake.Value
	}
	var auth map[string]config.AuthProvider
	if root.Decode(&auth) == nil {
		info.IsOAuth = auth[providerName].IsOAuth()
		info.IsLegacy = info.IsOAuth && auth[providerName].Type != "openai_chatgpt"
		for _, field := range []string{"access", "refresh", "expires", "account_id"} {
			info.IsLegacy = info.IsLegacy || getMapField(providerAuth, field) != nil
		}
		cfg := &config.Config{Auth: auth}
		if creds := cfg.GetOAuthCredentials(providerName); creds != nil {
			info.Credentials = creds
			info.Identity = subscriptionAccountIdentity(auth[config.ChatGPTAccountsKey].Registrations, creds.RegistrationKey())
		}
	}
	return info
}

func (a *ConfiguratorApp) saveAuthEntry(name, apiKey, apiKeyEnv string) {
	if a.authEdits == nil {
		a.authEdits = make(map[string]authEdit)
	}
	a.authEdits[name] = authEdit{apiKey: apiKey, apiKeyEnv: apiKeyEnv}
	if a.authNode == nil || unwrapDoc(a.authNode) == nil {
		a.authNode = &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode, Tag: "!!map"}}}
	}

	root := unwrapDoc(a.authNode)
	if root == nil {
		return
	}

	entryNode := ensureMapEntry(root, name)
	entryNode.Content = nil

	if apiKey != "" {
		entryNode.Content = append(entryNode.Content, newScalarNode("api_key"), newScalarNode(apiKey))
	}
	if apiKeyEnv != "" {
		entryNode.Content = append(entryNode.Content, newScalarNode("api_key_env"), newScalarNode(apiKeyEnv))
	}

	a.MarkDirtyAuth()
}

func (a *ConfiguratorApp) deleteAuthEntry(name string) {
	if a.authEdits == nil {
		a.authEdits = make(map[string]authEdit)
	}
	a.authEdits[name] = authEdit{remove: true}
	if a.authNode == nil {
		return
	}
	root := unwrapDoc(a.authNode)
	if root == nil {
		return
	}
	removeMapField(root, name)
	a.MarkDirtyAuth()
}

func maskKey(key string) string {
	if len(key) <= 8 {
		return "****"
	}
	return key[:4] + "..." + key[len(key)-4:]
}

type Layers struct {
	BuiltinNode *yaml.Node
	UserNode    *yaml.Node
	ProjectNode *yaml.Node
	Effective   *yaml.Node

	UserPath    string
	ProjectPath string

	EditTarget Layer
}

func LoadLayers(userPath, cwd string) (*Layers, error) {
	l := &Layers{
		UserPath: userPath,
	}

	builtinNode, err := config.LoadBuiltinNode()
	if err != nil {
		return nil, fmt.Errorf("loading builtin: %w", err)
	}
	l.BuiltinNode = builtinNode

	if userNode, err := loadYAMLNode(userPath); err == nil {
		l.UserNode = userNode
	}

	if cwd != "" {
		l.ProjectPath = config.ProjectConfigPath(cwd)
		if projectNode, err := loadYAMLNode(l.ProjectPath); err == nil {
			l.ProjectNode = projectNode
		}
	}

	if err := l.recompute(); err != nil {
		return nil, err
	}

	return l, nil
}

func (l *Layers) recompute() error {
	// Use the same filtered baseline for effective values and edit diffs.
	base := copyNode(l.BuiltinNode)
	if base == nil {
		var err error
		base, err = config.LoadBuiltinNode()
		if err != nil {
			return err
		}
	}

	if l.UserNode != nil {
		userCopy := copyNode(l.UserNode)
		config.MergeNodes(base, userCopy)
	}

	if l.ProjectNode != nil {
		projectCopy := copyNode(l.ProjectNode)
		if err := config.MergeProjectConfig(base, projectCopy); err != nil {
			return err
		}
	}

	config.ExpandTokens(base)
	config.StripSentinels(base)

	l.Effective = base
	return nil
}

func (l *Layers) Recompute() error {
	return l.recompute()
}

func (l *Layers) EditNode() *yaml.Node {
	switch l.EditTarget {
	case LayerProject:
		return l.ProjectNode
	default:
		return l.UserNode
	}
}

func (l *Layers) EditPath() string {
	switch l.EditTarget {
	case LayerProject:
		return l.ProjectPath
	default:
		return l.UserPath
	}
}

func (l *Layers) EffectiveForEditTarget() *yaml.Node {
	if l == nil {
		return nil
	}
	return l.EffectiveForLayer(l.EditTarget)
}

// BaseForEditTarget returns the effective lower layers that an edit should be
// diffed against. User edits inherit builtin config; project edits inherit
// builtin+user config.
func (l *Layers) BaseForEditTarget() *yaml.Node {
	if l == nil {
		return nil
	}
	if l.EditTarget == LayerProject {
		return l.EffectiveForLayer(LayerUser)
	}
	return copyNode(l.BuiltinNode)
}

// EffectiveForLayer returns only the layers visible at target: builtin+user
// for global config and builtin+user+project for current-working-directory config.
func (l *Layers) EffectiveForLayer(target Layer) *yaml.Node {
	if l == nil {
		return nil
	}
	if target == LayerProject {
		return l.Effective
	}
	base := copyNode(l.BuiltinNode)
	if base == nil {
		return nil
	}
	if l.UserNode != nil {
		config.MergeNodes(base, copyNode(l.UserNode))
	}
	config.ExpandTokens(base)
	config.StripSentinels(base)
	return base
}

func copyNode(n *yaml.Node) *yaml.Node {
	if n == nil {
		return nil
	}
	cp := *n
	if n.Kind == yaml.MappingNode || n.Kind == yaml.SequenceNode || n.Kind == yaml.DocumentNode {
		cp.Content = make([]*yaml.Node, len(n.Content))
		for i, child := range n.Content {
			cp.Content[i] = copyNode(child)
		}
	}
	return &cp
}

func unwrapDoc(node *yaml.Node) *yaml.Node {
	return config.UnwrapDoc(node)
}

func loadYAMLNode(path string) (*yaml.Node, error) {
	return config.LoadFileNode(path)
}

func writeYAMLNode(node *yaml.Node, path string) error {
	data, err := encodeYAMLNode(node)
	if err != nil {
		return err
	}

	dir := path
	if idx := strings.LastIndex(path, "/"); idx >= 0 {
		dir = path[:idx]
	}
	if err := os.MkdirAll(dir, 0755); err != nil {
		return fmt.Errorf("creating directory %s: %w", dir, err)
	}

	tmp, err := os.CreateTemp(dir, ".config-*.tmp")
	if err != nil {
		return fmt.Errorf("creating temp file: %w", err)
	}
	tmpName := tmp.Name()

	if _, err := tmp.Write(data); err != nil {
		tmp.Close()
		os.Remove(tmpName)
		return fmt.Errorf("writing temp file: %w", err)
	}
	if err := tmp.Close(); err != nil {
		os.Remove(tmpName)
		return fmt.Errorf("closing temp file: %w", err)
	}

	if err := os.Rename(tmpName, path); err != nil {
		os.Remove(tmpName)
		return fmt.Errorf("renaming temp file: %w", err)
	}

	return nil
}

func encodeYAMLNode(node *yaml.Node) ([]byte, error) {
	var buf bytes.Buffer
	enc := yaml.NewEncoder(&buf)
	enc.SetIndent(4)
	if err := enc.Encode(node); err != nil {
		return nil, fmt.Errorf("encoding yaml: %w", err)
	}
	if err := enc.Close(); err != nil {
		return nil, fmt.Errorf("closing yaml encoder: %w", err)
	}
	return buf.Bytes(), nil
}

func getMapField(mapping *yaml.Node, key string) *yaml.Node {
	if mapping == nil {
		return nil
	}
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			return mapping.Content[i+1]
		}
	}
	return nil
}

func setMapNullField(mapping *yaml.Node, key string) bool {
	if mapping == nil || mapping.Kind != yaml.MappingNode {
		return false
	}
	nullNode := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			old := mapping.Content[i+1]
			if old.Kind == yaml.ScalarNode && old.Tag == "!!null" {
				return false
			}
			mapping.Content[i+1] = nullNode
			return true
		}
	}
	mapping.Content = append(mapping.Content, newScalarNode(key), nullNode)
	return true
}

func setMapField(mapping *yaml.Node, key, value string) bool {
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			if mapping.Content[i+1].Value == value {
				return false
			}
			mapping.Content[i+1].Value = value
			mapping.Content[i+1].Kind = yaml.ScalarNode
			mapping.Content[i+1].Tag = "!!str"
			if needsYAML11Quoting(value) {
				mapping.Content[i+1].Style = yaml.DoubleQuotedStyle
			} else {
				mapping.Content[i+1].Style = 0
			}
			return true
		}
	}
	keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key, Tag: "!!str"}
	valNode := newScalarNode(value)
	mapping.Content = append(mapping.Content, keyNode, valNode)
	return true
}

func setBoolField(mapping *yaml.Node, key string, value bool) bool {
	str := "false"
	tag := "!!bool"
	if value {
		str = "true"
	}
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			if mapping.Content[i+1].Value == str {
				return false
			}
			mapping.Content[i+1].Value = str
			mapping.Content[i+1].Kind = yaml.ScalarNode
			mapping.Content[i+1].Tag = tag
			return true
		}
	}
	keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key, Tag: "!!str"}
	valNode := &yaml.Node{Kind: yaml.ScalarNode, Value: str, Tag: tag}
	mapping.Content = append(mapping.Content, keyNode, valNode)
	return true
}

func setIntField(mapping *yaml.Node, key string, value int) {
	str := fmt.Sprintf("%d", value)
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			mapping.Content[i+1].Value = str
			mapping.Content[i+1].Kind = yaml.ScalarNode
			mapping.Content[i+1].Tag = "!!int"
			return
		}
	}
	keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key, Tag: "!!str"}
	valNode := &yaml.Node{Kind: yaml.ScalarNode, Value: str, Tag: "!!int"}
	mapping.Content = append(mapping.Content, keyNode, valNode)
}

func removeMapField(mapping *yaml.Node, key string) bool {
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			mapping.Content = append(mapping.Content[:i], mapping.Content[i+2:]...)
			return true
		}
	}
	return false
}

func ensureMapEntry(mapping *yaml.Node, key string) *yaml.Node {
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			return mapping.Content[i+1]
		}
	}
	keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key, Tag: "!!str"}
	valNode := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
	mapping.Content = append(mapping.Content, keyNode, valNode)
	return valNode
}

func ensureSequenceField(mapping *yaml.Node, key string) *yaml.Node {
	for i := 0; i < len(mapping.Content)-1; i += 2 {
		if mapping.Content[i].Value == key {
			if mapping.Content[i+1].Kind == yaml.SequenceNode {
				return mapping.Content[i+1]
			}
		}
	}
	keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key, Tag: "!!str"}
	seqNode := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}
	mapping.Content = append(mapping.Content, keyNode, seqNode)
	return seqNode
}

func newScalarNode(value string) *yaml.Node {
	n := &yaml.Node{Kind: yaml.ScalarNode, Value: value, Tag: "!!str"}
	if needsYAML11Quoting(value) {
		n.Style = yaml.DoubleQuotedStyle
	}
	return n
}

func newIntNode(value int) *yaml.Node {
	return &yaml.Node{Kind: yaml.ScalarNode, Value: fmt.Sprintf("%d", value), Tag: "!!int"}
}

// needsYAML11Quoting reports whether a !!str scalar value would be misresolved
// as a bool or null by a YAML 1.1 reader (e.g. pyyaml, js-yaml) when emitted
// unquoted. yaml.v3's own emitter already handles YAML 1.1 numeric and
// canonical-case bool/null literals (true, True, 123, 1.5, null, ~), but it
// does NOT quote the non-canonical boolean keywords `on`/`off`/`yes`/`no`
// (any case) that YAML 1.1 also coerces to bool. The ez-agent config uses
// `on`/`off` as string values inside `thinking_levels`, and any third-party
// YAML 1.1 reader consuming the configurator's output (or a config round-
// tripped through such a reader) would silently corrupt them to `true`/
// `false`. Force double-quoting for any value matching these literals so the
// emitted YAML is safe for YAML 1.1 and 1.2 readers alike.
var yaml11BoolLiteralRe = regexp.MustCompile(`^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$`)
var yaml11NullLiteralRe = regexp.MustCompile(`^(?:~|null|Null|NULL|)$`)

func needsYAML11Quoting(s string) bool {
	return yaml11BoolLiteralRe.MatchString(s) || yaml11NullLiteralRe.MatchString(s)
}

func newMapNode() *yaml.Node {
	return &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
}

func removeFromSequence(seq *yaml.Node, value string) bool {
	for i, item := range seq.Content {
		if item.Kind == yaml.ScalarNode && item.Value == value {
			seq.Content = append(seq.Content[:i], seq.Content[i+1:]...)
			return true
		}
	}
	return false
}

func sequenceContains(seq *yaml.Node, value string) bool {
	for _, item := range seq.Content {
		if item.Kind == yaml.ScalarNode && item.Value == value {
			return true
		}
	}
	return false
}

func appendToSequence(seq *yaml.Node, item *yaml.Node) {
	seq.Content = append(seq.Content, item)
}

func parseKNumber(s string) int {
	s = strings.TrimSpace(s)
	if len(s) == 0 {
		return 0
	}
	mult := 1
	low := strings.ToLower(s)
	switch {
	case strings.HasSuffix(low, "m"):
		mult = 1048576
		s = s[:len(s)-1]
	case strings.HasSuffix(low, "k"):
		mult = 1024
		s = s[:len(s)-1]
	}
	var val int
	fmt.Sscanf(strings.TrimSpace(s), "%d", &val)
	return val * mult
}

func formatKNumber(n int) string {
	if n <= 0 {
		return ""
	}
	if n%1048576 == 0 {
		return fmt.Sprintf("%dm", n/1048576)
	}
	if n%1024 == 0 && n >= 1024 {
		return fmt.Sprintf("%dk", n/1024)
	}
	return fmt.Sprintf("%d", n)
}

func parseCommaList(s string) []string {
	s = strings.TrimSpace(s)
	if s == "" {
		return nil
	}
	parts := strings.Split(s, ",")
	var out []string
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p != "" {
			out = append(out, p)
		}
	}
	return out
}

func formatCommaList(items []string) string {
	return strings.Join(items, ", ")
}

func seqToStrings(seq *yaml.Node) []string {
	if seq == nil || seq.Kind != yaml.SequenceNode {
		return nil
	}
	var out []string
	for _, item := range seq.Content {
		if item.Kind == yaml.ScalarNode {
			out = append(out, item.Value)
		}
	}
	return out
}

func stringSlicesEqual(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

func stringSliceContains(slice []string, val string) bool {
	for _, s := range slice {
		if s == val {
			return true
		}
	}
	return false
}

func writeScalarSeqDiff(parent *yaml.Node, key string, desired, base []string) {
	if stringSlicesEqual(desired, base) {
		removeMapField(parent, key)
		return
	}
	seq := ensureSequenceField(parent, key)
	seq.Content = nil
	desiredSet := make(map[string]bool, len(desired))
	for _, item := range desired {
		seq.Content = append(seq.Content, newScalarNode(item))
		desiredSet[item] = true
	}
	for _, item := range base {
		if !desiredSet[item] {
			seq.Content = append(seq.Content, newScalarNode("~"+item))
		}
	}
}