package main

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

const (
	dtoFilePath     = "../frontend/src/types/dto.ts"
	importStatement = `import { Nullable } from "./nullable";`
)

func main() {
	// Run Tygo first
	fmt.Println("🔄 Running tygo...")
	if err := runTygo(); err != nil {
		fmt.Println("❌ Error running tygo:", err)
		os.Exit(1)
	}

	// Read dto.ts file
	content, err := os.ReadFile(dtoFilePath)
	if err != nil {
		fmt.Println("❌ Could not read dto.ts:", err)
		os.Exit(1)
	}

	// Convert to string
	dtoContent := string(content)

	// Check if import already exists
	if strings.Contains(dtoContent, importStatement) {
		fmt.Println("ℹ️ Import already exists in dto.ts, skipping.")
		return
	}

	// Add import statement at the beginning
	newContent := importStatement + "\n" + dtoContent
	if err := os.WriteFile(dtoFilePath, []byte(newContent), 0644); err != nil {
		fmt.Println("❌ Error writing dto.ts:", err)
		os.Exit(1)
	}

	fmt.Println("✅ Successfully added Nullable<T> import to dto.ts")
}

// Runs Tygo command
func runTygo() error {
	cmd := "tygo"
	output, err := exec.Command(cmd, "generate").CombinedOutput()
	if err != nil {
		fmt.Println("Tygo output:", string(output))
		return err
	}
	if len(output) > 0 {
		fmt.Println("Tygo output:", string(output))
		return nil
	}
	return nil
}
