package executor

import (
	"html"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

// titleTagRe matches the document <title> element (first occurrence is used).
var titleTagRe = regexp.MustCompile(`(?is)<title[^>]*>.*?</title>`)

// ApplyProjectTitle rewrites the workspace's root index.html <title> to the
// project's display name. Templates ship a stock placeholder title, so this
// runs right after template extraction — before the agent touches anything —
// making the generated site's tab title deterministic. No-ops when the name
// is blank, the file is missing (WordPress themes have no root index.html),
// or there is no <title> tag.
func ApplyProjectTitle(workspacePath, projectName string) error {
	name := strings.TrimSpace(projectName)
	if name == "" {
		return nil
	}

	indexPath := filepath.Join(workspacePath, "index.html")
	content, err := os.ReadFile(indexPath)
	if err != nil {
		return nil // no root index.html — nothing to title
	}

	loc := titleTagRe.FindIndex(content)
	if loc == nil {
		return nil
	}

	title := "<title>" + html.EscapeString(name) + "</title>"
	updated := string(content[:loc[0]]) + title + string(content[loc[1]:])
	return os.WriteFile(indexPath, []byte(updated), 0644)
}
