package platform

import (
	"fmt"
	"sort"
	"sync"
)

var (
	factoryMu sync.Mutex
	factories = make(map[string]PlatformFactory)
)

// RegisterPlatform registers a platform factory for self-registration.
// Called from platform init() functions.
// Panics if platform ID is already registered (catches configuration mistakes early).
func RegisterPlatform(platformID string, factory PlatformFactory) {
	factoryMu.Lock()
	defer factoryMu.Unlock()

	if _, exists := factories[platformID]; exists {
		panic(fmt.Sprintf("platform %q already registered", platformID))
	}
	factories[platformID] = factory
}

// ListRegisteredPlatforms returns IDs of all registered platforms (sorted).
func ListRegisteredPlatforms() []string {
	factoryMu.Lock()
	defer factoryMu.Unlock()

	ids := make([]string, 0, len(factories))
	for id := range factories {
		ids = append(ids, id)
	}
	sort.Strings(ids)
	return ids
}

// ClearRegistrations resets all registrations.
// Used for testing to ensure test isolation.
func ClearRegistrations() {
	factoryMu.Lock()
	defer factoryMu.Unlock()
	factories = make(map[string]PlatformFactory)
}

// getFactories returns a copy of registered factories.
// Internal use only - called by NewRegistry().
func getFactories() map[string]PlatformFactory {
	factoryMu.Lock()
	defer factoryMu.Unlock()

	copy := make(map[string]PlatformFactory, len(factories))
	for k, v := range factories {
		copy[k] = v
	}
	return copy
}

// HasRegisteredPlatforms returns true if any platforms are registered.
func HasRegisteredPlatforms() bool {
	factoryMu.Lock()
	defer factoryMu.Unlock()
	return len(factories) > 0
}
