extends Node
## Settings Service
##
## Singleton service for application configuration.
## Stores URLs, feature flags, and other runtime settings.
##
## Usage:
##   Settings.get_api_url()
##   Settings.get_web_url()
##   Settings.set_environment("production")

# Environment types
enum Env {
	DEVELOPMENT,
	STAGING,
	PRODUCTION
}

# Current environment
var _current_environment: int = Env.DEVELOPMENT

# URL Configuration
var _api_urls := {
	Env.DEVELOPMENT: "http://localhost:5000",
	Env.STAGING: "https://staging-api.codeofconquest.com",
	Env.PRODUCTION: "https://api.codeofconquest.com"
}

var _web_urls := {
	Env.DEVELOPMENT: "http://localhost:8000",  # Flask serves web pages in dev
	Env.STAGING: "https://staging.codeofconquest.com",
	Env.PRODUCTION: "https://www.codeofconquest.com"
}

# Feature flags
var _features := {
	"enable_debug_logging": true,
	"enable_analytics": false,
	"enable_multiplayer": false,
	"max_characters_per_user": 5
}

# User preferences (persisted)
var _preferences := {
	"remember_login": true,
	"auto_save": true,
	"sound_enabled": true,
	"music_enabled": true,
	"sound_volume": 0.8,
	"music_volume": 0.6
}

# Save file configuration
const SETTINGS_FILE_PATH := "user://settings.save"
const SETTINGS_VERSION := 1


func _ready() -> void:
	_load_settings()
	_detect_environment()
	print("[Settings] Service initialized")
	print("[Settings] Environment: %s" % _environment_to_string(_current_environment))
	print("[Settings] API URL: %s" % get_api_url())
	print("[Settings] Web URL: %s" % get_web_url())


## Get current API base URL
func get_api_url() -> String:
	return _api_urls.get(_current_environment, _api_urls[Env.DEVELOPMENT])


## Get current web frontend base URL
func get_web_url() -> String:
	return _web_urls.get(_current_environment, _web_urls[Env.DEVELOPMENT])


## Get current environment
func get_environment() -> int:
	return _current_environment


## Set environment (for testing/switching)
func set_environment(env: int) -> void:
	_current_environment = env
	print("[Settings] Environment changed to: %s" % _environment_to_string(env))
	print("[Settings] API URL: %s" % get_api_url())
	print("[Settings] Web URL: %s" % get_web_url())


## Check if a feature is enabled
func is_feature_enabled(feature_name: String) -> bool:
	return _features.get(feature_name, false)


## Get feature value
func get_feature(feature_name: String, default: Variant = null) -> Variant:
	return _features.get(feature_name, default)


## Set feature flag (for testing/debugging)
func set_feature(feature_name: String, value: Variant) -> void:
	_features[feature_name] = value
	print("[Settings] Feature updated: %s = %s" % [feature_name, value])


## Get user preference
func get_preference(key: String, default: Variant = null) -> Variant:
	return _preferences.get(key, default)


## Set user preference
func set_preference(key: String, value: Variant) -> void:
	_preferences[key] = value
	print("[Settings] Preference updated: %s = %s" % [key, value])
	_save_settings()


## Get all preferences
func get_all_preferences() -> Dictionary:
	return _preferences.duplicate()


## Auto-detect environment based on OS and build flags
func _detect_environment() -> void:
	# Check for --production command line argument
	var args := OS.get_cmdline_args()
	if "--production" in args:
		_current_environment = Env.PRODUCTION
		return

	if "--staging" in args:
		_current_environment = Env.STAGING
		return

	# Default to development
	_current_environment = Env.DEVELOPMENT


## Save settings to disk
func _save_settings() -> void:
	var save_data := {
		"version": SETTINGS_VERSION,
		"preferences": _preferences,
		"timestamp": Time.get_unix_time_from_system()
	}

	var file := FileAccess.open(SETTINGS_FILE_PATH, FileAccess.WRITE)
	if file == null:
		push_error("[Settings] Failed to open settings file for writing: %s" % FileAccess.get_open_error())
		return

	file.store_string(JSON.stringify(save_data))
	file.close()

	print("[Settings] Settings saved to %s" % SETTINGS_FILE_PATH)


## Load settings from disk
func _load_settings() -> void:
	if not FileAccess.file_exists(SETTINGS_FILE_PATH):
		print("[Settings] No settings file found, using defaults")
		return

	var file := FileAccess.open(SETTINGS_FILE_PATH, FileAccess.READ)
	if file == null:
		push_error("[Settings] Failed to open settings file for reading: %s" % FileAccess.get_open_error())
		return

	var json_string := file.get_as_text()
	file.close()

	var json := JSON.new()
	var parse_error := json.parse(json_string)

	if parse_error != OK:
		push_error("[Settings] Failed to parse settings file")
		return

	var save_data: Dictionary = json.data

	# Check version
	if save_data.get("version", 0) != SETTINGS_VERSION:
		print("[Settings] Settings file version mismatch, using defaults")
		return

	# Restore preferences
	var saved_prefs = save_data.get("preferences", {})
	for key in saved_prefs:
		_preferences[key] = saved_prefs[key]

	print("[Settings] Settings loaded from %s" % SETTINGS_FILE_PATH)


## Convert environment enum to string
func _environment_to_string(env: int) -> String:
	match env:
		Env.DEVELOPMENT:
			return "Development"
		Env.STAGING:
			return "Staging"
		Env.PRODUCTION:
			return "Production"
		_:
			return "Unknown"
