package executor

import (
	"regexp"
	"sort"
	"strings"
)

var cssVarRe = regexp.MustCompile(`--([a-z0-9-]+)\s*:\s*([^;]+);`)

// parseCSSVars extracts the --var declarations from the first CSS block opened
// by the given selector (":root" or ".dark") in a design system's tokens.css.
func parseCSSVars(css, selector string) map[string]string {
	out := map[string]string{}
	idx := strings.Index(css, selector+" {")
	if idx < 0 {
		idx = strings.Index(css, selector+"{")
	}
	if idx < 0 {
		return out
	}
	open := strings.Index(css[idx:], "{")
	if open < 0 {
		return out
	}
	body := css[idx+open+1:]
	if end := strings.Index(body, "}"); end >= 0 {
		body = body[:end]
	}
	for _, m := range cssVarRe.FindAllStringSubmatch(body, -1) {
		out[m[1]] = strings.TrimSpace(m[2])
	}
	return out
}

// wpPaletteSpec maps curated WordPress palette slugs to design-token vars.
// base/contrast are the de-facto core-theme slugs (pattern interop).
var wpPaletteSpec = []struct{ wpSlug, tokenVar, name string }{
	{"base", "background", "Base"},
	{"contrast", "foreground", "Contrast"},
	{"primary", "primary", "Primary"},
	{"primary-foreground", "primary-foreground", "Primary Foreground"},
	{"secondary", "secondary", "Secondary"},
	{"secondary-foreground", "secondary-foreground", "Secondary Foreground"},
	{"muted", "muted", "Muted"},
	{"muted-foreground", "muted-foreground", "Muted Foreground"},
	{"border", "border", "Border"},
}

// buildWPPalette builds the WordPress palette from base token vars overlaid
// with accent vars. Falls back to the accent map minus UI-only slugs (ring,
// chart-*, sidebar-*) when the tokens yield nothing usable.
func buildWPPalette(base, accent map[string]string) []map[string]string {
	merged := map[string]string{}
	for k, v := range base {
		merged[k] = v
	}
	for k, v := range accent {
		merged[k] = v
	}

	var palette []map[string]string
	for _, spec := range wpPaletteSpec {
		if css := hslTokenToCSS(merged[spec.tokenVar]); css != "" {
			palette = append(palette, map[string]string{
				"slug": spec.wpSlug, "name": spec.name, "color": css,
			})
		}
	}
	if len(palette) > 0 {
		return palette
	}

	slugs := make([]string, 0, len(accent))
	for slug := range accent {
		if slug == "ring" || strings.HasPrefix(slug, "chart-") || strings.HasPrefix(slug, "sidebar-") {
			continue
		}
		slugs = append(slugs, slug)
	}
	sort.Strings(slugs)
	for _, slug := range slugs {
		if css := hslTokenToCSS(accent[slug]); css != "" {
			palette = append(palette, map[string]string{
				"slug": slug, "name": capitalize(slug), "color": css,
			})
		}
	}
	return palette
}
