package builder

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
)

func writeIconAndVersionWinresJSON(fullWinresPath string) (string, error) {
	data, err := os.ReadFile(fullWinresPath)
	if err != nil {
		return "", err
	}
	var doc map[string]json.RawMessage
	if err := json.Unmarshal(data, &doc); err != nil {
		return "", err
	}
	icons, ok := doc["RT_GROUP_ICON"]
	if !ok || len(icons) == 0 || string(icons) == "null" {
		return "", fmt.Errorf("prep exe has no RT_GROUP_ICON resources")
	}
	outDoc := map[string]json.RawMessage{"RT_GROUP_ICON": icons}
	if version, hasVersion := doc["RT_VERSION"]; hasVersion && len(version) > 0 && string(version) != "null" {
		outDoc["RT_VERSION"] = version
	}
	out, err := json.MarshalIndent(outDoc, "", "  ")
	if err != nil {
		return "", err
	}
	outPath := filepath.Join(filepath.Dir(fullWinresPath), "filtered.json")
	if err := os.WriteFile(outPath, out, 0644); err != nil {
		return "", err
	}
	return outPath, nil
}
