package tsrpc

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
)

type TSFiles map[string]string

func (t *TSFiles) Add(name string, source string) {
	if t == nil || *t == nil {
		*t = make(map[string]string)
	}
	if (*t)[name] == "" {
		(*t)[name] = source
	} else {
		(*t)[name] += source
	}
}

func (t *TSFiles) Get(name string) (string, bool) {
	if t == nil || *t == nil {
		return "", false
	}
	s, ok := (*t)[name]
	return s, ok
}

func (t *TSFiles) Save() error {
	if t == nil || *t == nil {
		return fmt.Errorf("TS Files not initialized")
	}

	for k, v := range *t {
		fmt.Printf("file: %s\nsource:\n%s\n\n", k, v)
	}

	for name, source := range *t {
		formatted, err := formatJS(source)
		if err != nil {
			return fmt.Errorf("format JS: %w", err)
		}

		err = os.WriteFile(fmt.Sprintf("GeneratedCode/%s", name), []byte(formatted), 0644)
		if err != nil {
			return fmt.Errorf("write local generated typescript: %w", err)
		}
	}
	return nil
}

func formatJS(src string) (string, error) {
	// Se hai prettier globale:
	cmd := exec.Command("prettier", "--parser", "typescript", "--use-tabs", "false", "--tab-width", "2")

	// Se hai prettier solo come devDependency:
	// cmd := exec.Command("npx", "prettier", "--parser", "typescript")

	cmd.Stdin = bytes.NewBufferString(src)

	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		// Stampa anche lo stderr di Prettier, così vedi l’errore reale
		return "", fmt.Errorf("prettier error: %v\nstderr: %s", err, stderr.String())
	}

	return out.String(), nil
}
