# 文件名: start.gd
# 场景的根节点脚本，通常用于处理主菜单或启动界面的逻辑。
extends Node2D

# --- 节点引用 ---
# !! 重要：请根据你的实际场景结构调整以下节点路径 !!
@onready var new_game_button = $UI/Select_List/New
@onready var load_game_button = $UI/Select_List/Load
# @onready var error_message_label = $UI/ErrorMessageLabel # 如果有错误提示标签

# --- 场景路径 ---
var GameScene_path = "res://Entity/Level/GameScene.tscn"

# --- Godot 生命周期方法 ---

func _ready():
	print("Start Scene: Initializing...")
	# --- 连接 UI 信号 ---
	if new_game_button:
		new_game_button.pressed.connect(_on_new_game_pressed)
		print("Start Scene: Connected 'pressed' signal for New Game button.")
	else:
		printerr("Start Scene Error: New Game button node not found at path specified in @onready var.")

	if load_game_button:
		load_game_button.pressed.connect(_on_load_game_pressed)
		print("Start Scene: Connected 'pressed' signal for Load Game button.")
		# 示例：根据存档是否存在禁用加载按钮 (需要 SaveLoadManager Autoload)
		# if ProjectSettings.has_setting("autoload/SaveLoadManager"):
		#	 load_game_button.disabled = !SaveLoadManager.does_save_exist(1) # 假设检查槽位1
		# else:
		#	 printerr("Start Scene Warning: SaveLoadManager Autoload not found, cannot check save existence for button state.")
	else:
		printerr("Start Scene Error: Load Game button node not found at path specified in @onready var.")

	# --- 连接 InitializationManager 信号 ---
	# 确保 InitializationManager 是 Autoload 并且已经注册
	if ProjectSettings.has_setting("autoload/InitializationManager"):
		# 连接新游戏初始化完成信号
		if not InitializationManager.is_connected("new_game_initialized", Callable(self, "_on_initialization_complete")):
			InitializationManager.new_game_initialized.connect(_on_initialization_complete)
			print("Start Scene: Connected to InitializationManager.new_game_initialized signal.")

		# 连接加载游戏完成信号
		if not InitializationManager.is_connected("game_loaded", Callable(self, "_on_initialization_complete")):
			InitializationManager.game_loaded.connect(_on_initialization_complete)
			print("Start Scene: Connected to InitializationManager.game_loaded signal.")
	else:
		# 如果没有配置 Autoload，这是一个严重错误
		printerr("Start Scene Error: InitializationManager Autoload is not configured in Project Settings!")
		# 在这种情况下，游戏可能无法正常启动新游戏或加载
		if new_game_button: new_game_button.disabled = true
		if load_game_button: load_game_button.disabled = true

# 当此节点从场景树中移除时调用
func _exit_tree():
	# 断开与 Autoload 信号的连接，这是一个良好的实践
	if ProjectSettings.has_setting("autoload/InitializationManager"):
		# 断开新游戏信号
		if InitializationManager.is_connected("new_game_initialized", Callable(self, "_on_initialization_complete")):
			InitializationManager.new_game_initialized.disconnect(Callable(self, "_on_initialization_complete"))
			print("Start Scene: Disconnected from InitializationManager.new_game_initialized signal.")
		# 断开加载游戏信号
		if InitializationManager.is_connected("game_loaded", Callable(self, "_on_initialization_complete")):
			InitializationManager.game_loaded.disconnect(Callable(self, "_on_initialization_complete"))
			print("Start Scene: Disconnected from InitializationManager.game_loaded signal.")

# --- UI 信号回调函数 ---

# 当“新游戏”按钮被按下时调用
func _on_new_game_pressed():
	print("Start Scene: 'New Game' button pressed. Requesting new game initialization...")
	if new_game_button: new_game_button.disabled = true
	if load_game_button: load_game_button.disabled = true

	if ProjectSettings.has_setting("autoload/InitializationManager"):
		# 调用 InitializationManager 启动流程
		# start_new_game_process 返回 true/false 表示调用是否成功启动（例如数据加载失败）
		if not InitializationManager.start_new_game_process():
			# 如果启动流程本身就失败了（例如 InitialDataManager 无法加载数据）
			printerr("Start Scene: InitializationManager.start_new_game_process() failed immediately.")
			# 显示错误信息给用户
			# if error_message_label: error_message_label.text = "无法启动新游戏，请检查配置。"
			# 重新启用按钮
			if new_game_button: new_game_button.disabled = false
			if load_game_button: load_game_button.disabled = false
		# else: # 如果启动成功，则等待 _on_initialization_complete 信号
			# print("Start Scene: New game process started, waiting for completion signal...")
	else:
		printerr("Start Scene Error: Cannot start new game - InitializationManager Autoload not found!")
		if new_game_button: new_game_button.disabled = false
		if load_game_button: load_game_button.disabled = false


# 当“加载游戏”按钮被按下时调用
func _on_load_game_pressed():
	var slot_to_load = 1 # <-- 硬编码加载的存档槽位 ID
	print("Start Scene: 'Load Game' button pressed. Requesting load for slot " + str(slot_to_load) + "...")

	if new_game_button: new_game_button.disabled = true
	if load_game_button: load_game_button.disabled = true

	# --- 需要 SaveLoadManager 来获取存档数据 ---
	if not ProjectSettings.has_setting("autoload/SaveLoadManager"):
		printerr("Start Scene Error: Cannot load game - SaveLoadManager Autoload not found!")
		if new_game_button: new_game_button.disabled = false
		if load_game_button: load_game_button.disabled = false
		return # 无法继续

	# 1. 尝试从 SaveLoadManager 加载数据 (现在期望返回字典或 null)
	var loaded_data: Variant = SaveLoadManager.load_game(slot_to_load)

	# 2. 检查加载是否成功 (返回 null 表示失败)
	if loaded_data == null:
		printerr("Start Scene: Failed to load save data from slot " + str(slot_to_load) + " (SaveLoadManager returned null).")
		# 显示错误信息给用户
		# if error_message_label: error_message_label.text = "加载存档失败！"
		# 重新启用按钮
		if new_game_button: new_game_button.disabled = false
		if load_game_button: load_game_button.disabled = false
		return # 加载失败，中止

	# 2.1 (可选但推荐) 再次确认加载的数据是字典类型
	if not loaded_data is Dictionary:
		printerr("Start Scene Error: Loaded data from SaveLoadManager is not a Dictionary. Type:", typeof(loaded_data))
		if new_game_button: new_game_button.disabled = false
		if load_game_button: load_game_button.disabled = false
		return # 数据类型错误，中止

	# 3. 如果存档数据加载成功 (是字典)，再调用 InitializationManager 处理
	if ProjectSettings.has_setting("autoload/InitializationManager"):
		# 将加载到的字典传递给 load_game_process
		if not InitializationManager.load_game_process(loaded_data): # <--- 传递字典
			printerr("Start Scene: InitializationManager.load_game_process() failed.")
			# 显示错误信息给用户
			# if error_message_label: error_message_label.text = "应用存档状态时出错。"
			# 重新启用按钮
			if new_game_button: new_game_button.disabled = false
			if load_game_button: load_game_button.disabled = false
		# else: # 如果启动成功，则等待 _on_initialization_complete 信号
			# print("Start Scene: Load game process started, waiting for completion signal...")
	else:
		printerr("Start Scene Error: Cannot process loaded game - InitializationManager Autoload not found!")
		if new_game_button: new_game_button.disabled = false
		if load_game_button: load_game_button.disabled = false


# --- InitializationManager 信号回调函数 ---

# 当 InitializationManager 完成新游戏或加载游戏流程后，此函数被调用
func _on_initialization_complete(): # 移除了 success 参数
	print("Start Scene: Received initialization complete signal (New Game or Load).")
	# 既然信号被发出，我们认为初始化流程是成功的
	print("--------------------------------------------------")
	print("Start Scene: Initialization successful!")
	print("--------------------------------------------------")

	# 切换到主游戏场景
	Go_To_GameScene() # 保持不变

	# 注意：这里没有处理初始化失败的情况，因为失败应该在
	# start_new_game_process 或 load_game_process 返回 false 时，
	# 或者在 SaveLoadManager.load_game 失败时，在调用处直接处理。
	# 如果 InitializationManager 内部在发出信号前还可能失败，
	# 则需要重新考虑信号设计或错误处理流程。


# --- 辅助函数 ---

# 切换到主游戏场景 (保持不变)
func Go_To_GameScene():
	print("Start Scene: Attempting to switch to Game Scene:", GameScene_path)
	var err = get_tree().change_scene_to_file(GameScene_path)
	if err != OK:
		printerr("Start Scene CRITICAL ERROR: Failed to switch to main game scene!")
		printerr("  Path: " + GameScene_path)
		printerr("  Error code: " + str(err))
		# if error_message_label: error_message_label.text = "无法加载主游戏场景！"
