package tsgenerator

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

	"server/internal/config"
	tsrpc "server/pkg/ts-rpc"
)

func TsGenerate() (string, error) {
	path := "GeneratedCode"
	if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
		err := os.Mkdir(path, os.ModePerm)
		if err != nil {
			return "", fmt.Errorf("create GeneratedCode directory: %w", err)
		}
	}

	var tsSource = tsrpc.GetTSSource(tsrpc.TSConfig{Url: "http://localhost:3000", TsApi: nil, Path: "."})

	formatted, err1 := formatJS(tsSource)
	if err1 != nil {
		return "", err1
	}

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

	configPath := os.Getenv("CONFIG_PATH")
	if configPath == "" {
		configPath = "configs/config.json"
	}
	if _, err := config.LoadConfig(configPath); err != nil {
		return "", fmt.Errorf("load config from %s: %w", configPath, err)
	}

	frontendAPIPath := os.Getenv("FRONTEND_API_PATH")
	if frontendAPIPath == "" {
		return "", errors.New("FRONTEND_API_PATH must be set")
	}

	fmt.Printf("Saving generated TypeScript to %s\n", frontendAPIPath)

	err = os.WriteFile(frontendAPIPath+"/api.ts", []byte(formatted), 0644)
	if err != nil {
		return "", fmt.Errorf("write frontend api.ts: %w", err)
	}

	return formatted, 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

}
