package sandbox

// settings_module.go — v0.30.0 CS2
//
// The settings module lets extensions read their admin-configured and
// per-user settings. Always injected (no permission required — a package
// reads its own settings).
//
// Starlark API:
//   val = settings.get("key")            # returns string, number, bool, or None
//   val = settings.get("key", "default") # returns default if key not set

import (
	"context"
	"encoding/json"

	"go.starlark.net/starlark"
	"go.starlark.net/starlarkstruct"

	"chat-switchboard/store"
)

// BuildSettingsModule creates the "settings" Starlark module for a package.
// It reads from package_settings (admin-configured) merged with per-user
// settings when a userID is provided. Package-level settings are the base;
// user-level settings override.
func BuildSettingsModule(ctx context.Context, stores store.Stores, packageID string, userID string) *starlarkstruct.Module {
	return MakeModule("settings", starlark.StringDict{
		"get": starlark.NewBuiltin("settings.get", settingsGet(ctx, stores, packageID, userID)),
	})
}

func settingsGet(ctx context.Context, stores store.Stores, packageID string, userID string) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
	return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
		var key string
		var defaultVal starlark.Value = starlark.None
		if err := starlark.UnpackPositionalArgs("settings.get", args, kwargs, 1, &key, &defaultVal); err != nil {
			return nil, err
		}

		// Load package-level settings
		merged := make(map[string]any)
		if stores.Packages != nil {
			pkgSettings, err := stores.Packages.GetPackageSettings(ctx, packageID)
			if err == nil && len(pkgSettings) > 0 {
				json.Unmarshal([]byte(pkgSettings), &merged)
			}
		}

		// Overlay user-level settings if a user context is available
		if userID != "" && stores.Packages != nil {
			userSettings, err := stores.Packages.GetUserSettings(ctx, packageID, userID)
			if err == nil && userSettings != nil && len(userSettings.Settings) > 0 {
				var userMap map[string]any
				if json.Unmarshal([]byte(userSettings.Settings), &userMap) == nil {
					for k, v := range userMap {
						merged[k] = v
					}
				}
			}
		}

		val, ok := merged[key]
		if !ok {
			return defaultVal, nil
		}

		sv, err := goToStarlark(val)
		if err != nil {
			return defaultVal, nil
		}
		return sv, nil
	}
}
