// update-platforms scans internal/platforms/*/ for directories with register.go
// and updates app.go with the correct blank imports.
//
// This enables true plug-and-play: copy platform files, run make build, done.
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
)

const (
	modulePath   = "github.com/titansys/appy-builder"
	platformsDir = "internal/platforms"
	appGoPath    = "app.go"
)

func main() {
	// 1. Discover platforms with register.go
	platforms, err := discoverPlatforms(platformsDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error discovering platforms: %v\n", err)
		os.Exit(1)
	}

	if len(platforms) == 0 {
		fmt.Println("Warning: No platforms with register.go found")
	} else {
		fmt.Printf("Discovered platforms: %v\n", platforms)
	}

	// 2. Read app.go
	content, err := os.ReadFile(appGoPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error reading %s: %v\n", appGoPath, err)
		os.Exit(1)
	}

	// 3. Update import block between markers
	updated, changed := updateImports(string(content), platforms)

	if !changed {
		fmt.Println("No changes needed - platform imports already up to date")
		return
	}

	// 4. Write back
	if err := os.WriteFile(appGoPath, []byte(updated), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "Error writing %s: %v\n", appGoPath, err)
		os.Exit(1)
	}

	fmt.Println("Updated app.go with platform imports")
}

// discoverPlatforms scans baseDir for subdirectories containing register.go
func discoverPlatforms(baseDir string) ([]string, error) {
	entries, err := os.ReadDir(baseDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil // No platforms directory yet
		}
		return nil, err
	}

	var platforms []string
	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		registerPath := filepath.Join(baseDir, entry.Name(), "register.go")
		if _, err := os.Stat(registerPath); err == nil {
			platforms = append(platforms, entry.Name())
		}
	}

	sort.Strings(platforms)
	return platforms, nil
}

// updateImports replaces the import block between markers with discovered platforms
func updateImports(content string, platforms []string) (string, bool) {
	// Build import lines
	var imports []string
	for _, p := range platforms {
		imports = append(imports, fmt.Sprintf("\t_ \"%s/internal/platforms/%s\"", modulePath, p))
	}

	// Pattern to match between markers (including markers)
	// (?s) enables . to match newlines
	re := regexp.MustCompile(`(?s)// PLATFORM_IMPORTS_START\n.*?// PLATFORM_IMPORTS_END`)

	var replacement string
	if len(imports) > 0 {
		replacement = "// PLATFORM_IMPORTS_START\n" + strings.Join(imports, "\n") + "\n\t// PLATFORM_IMPORTS_END"
	} else {
		replacement = "// PLATFORM_IMPORTS_START\n\t// PLATFORM_IMPORTS_END"
	}

	if !re.MatchString(content) {
		fmt.Fprintf(os.Stderr, "Warning: Markers not found in %s\n", appGoPath)
		fmt.Fprintln(os.Stderr, "Expected markers:")
		fmt.Fprintln(os.Stderr, "  // PLATFORM_IMPORTS_START")
		fmt.Fprintln(os.Stderr, "  // PLATFORM_IMPORTS_END")
		return content, false
	}

	// Check if already matches
	match := re.FindString(content)
	if match == replacement {
		return content, false
	}

	updated := re.ReplaceAllString(content, replacement)
	return updated, true
}
