# InitializationManager.gd
# Autoload Singleton
# 负责协调游戏的初始化流程，包括启动新游戏和加载游戏。

extends Node

# 信号：当新游戏数据准备好，注入 GameState 后发出
signal new_game_initialized
# 信号：当从存档加载游戏数据，恢复 GameState 后发出
signal game_loaded

# --- 核心流程函数 ---

# 启动新游戏的处理流程
func start_new_game_process() -> bool:
	print("InitializationManager: Starting new game process...")

	# 1. 确保基础数据已加载
	if not InitialDataManager.ensure_data_loaded():
		printerr("InitializationManager: Failed to ensure initial data is loaded. Aborting new game.")
		return false

	# 2. 获取初始蓝图数据
	var settings_data = InitialDataManager.get_starting_settings()
	var task_dev_data = InitialDataManager.get_task_development_data()
	var npc_initial_data = InitialDataManager.get_npc_initial_data() # MODIFIED: 获取NPC初始数据

	# MODIFIED: 更新空值检查
	if settings_data.is_empty() or task_dev_data.is_empty() or npc_initial_data.is_empty():
		var error_msg = "InitializationManager: Failed to retrieve initial data. Aborting new game. Details:\n"
		if settings_data.is_empty(): error_msg += " - Settings data is empty.\n"
		if task_dev_data.is_empty(): error_msg += " - Task development data is empty.\n"
		if npc_initial_data.is_empty(): error_msg += " - NPC initial data is empty (check npc.json or InitialDataManager logs).\n"
		printerr(error_msg)
		return false

	# 3. 构建注入 GameState 的初始状态字典
	# MODIFIED: 传递 npc_initial_data 给 _build_initial_state
	var initial_state = _build_initial_state(settings_data, task_dev_data, npc_initial_data)
	if initial_state.is_empty(): # _build_initial_state 内部可能有错误检查导致返回空
		printerr("InitializationManager: Failed to build initial game state (returned empty). Aborting new game.")
		return false

	# 4. 初始化 GameState
	GameState.initialize_for_new_game(initial_state)
	print("InitializationManager: GameState initialized for new game.")

	# 5. 发出信号，通知其他系统新游戏已准备就绪
	new_game_initialized.emit()
	print("InitializationManager: New game initialized successfully.")
	return true

# 加载游戏的流程
func load_game_process(save_data: Dictionary) -> bool:
	print("InitializationManager: Starting load game process...")
	# 1. 确保基础数据已加载 (可能需要，以防某些静态数据需要参考)
	if not InitialDataManager.ensure_data_loaded():
		printerr("InitializationManager: Failed to ensure initial data is loaded during load game.")
		# 这里不一定需要中止，取决于后续逻辑是否依赖 InitialData
		# return false

	# 2. 使用存档数据恢复 GameState
	# 假设 save_data 就是从 SaveLoadManager.load_game 获取的 game_state 字典
	GameState.restore_state(save_data)
	print("InitializationManager: GameState restored from save data.")

	# 3. 发出信号，通知其他系统游戏已加载
	game_loaded.emit()
	print("InitializationManager: Game loaded successfully.")
	return true


# --- 内部辅助函数 ---

# MODIFIED: 函数签名增加了 npc_defs 参数
# 根据从 InitialDataManager 获取的蓝图数据，构建注入 GameState 的初始状态字典
func _build_initial_state(settings: Dictionary, task_dev: Dictionary, npc_defs: Dictionary) -> Dictionary:
	var initial_state: Dictionary = {}

	# 1. 合并基础设置 (Init_Base.json) - 这些保持为顶级键
	# 使用深拷贝确保数据独立
	initial_state.merge(settings.duplicate(true), true)

	# 2. 创建一个新的字典来存储所有与任务开发相关的动态状态 (以及需要的静态信息)
	var task_dev_state: Dictionary = {}

	# 3. 处理 Task Development 数据 (task_development.json)，将其存入 task_dev_state
	# ... (这部分关于 platforms, gameplays, themes, strategies, product_focus_points 的代码保持不变) ...
	# (为了简洁，我省略了这部分重复代码，请确保您保留了原有的task_dev_state构建逻辑)
	# --- START: task_dev_state 构建逻辑 (假设已存在) ---
	task_dev_state["platforms"] = {}
	if task_dev.has("platforms") and typeof(task_dev["platforms"]) == TYPE_DICTIONARY:
		for platform_key in task_dev["platforms"]:
			var p_data = task_dev["platforms"][platform_key]
			if typeof(p_data) == TYPE_DICTIONARY:
				task_dev_state["platforms"][platform_key] = p_data.duplicate(true)
			else:
				printerr("InitializationManager: Invalid data format for platform: ", platform_key)
	else:
		print("InitializationManager: No 'platforms' data found or invalid format in task_development.json")

	task_dev_state["gameplays"] = {}
	if task_dev.has("gameplays") and typeof(task_dev["gameplays"]) == TYPE_DICTIONARY:
		for gameplay_key in task_dev["gameplays"]:
			var g_data = task_dev["gameplays"][gameplay_key]
			if typeof(g_data) == TYPE_DICTIONARY:
				task_dev_state["gameplays"][gameplay_key] = g_data.duplicate(true)
			else:
				printerr("InitializationManager: Invalid data format for gameplay: ", gameplay_key)
	else:
		print("InitializationManager: No 'gameplays' data found or invalid format in task_development.json")

	task_dev_state["themes"] = {}
	if task_dev.has("themes") and typeof(task_dev["themes"]) == TYPE_DICTIONARY:
		for theme_key in task_dev["themes"]:
			var t_data = task_dev["themes"][theme_key]
			if typeof(t_data) == TYPE_DICTIONARY:
				task_dev_state["themes"][theme_key] = t_data.duplicate(true)
			else:
				printerr("InitializationManager: Invalid data format for theme: ", theme_key)
	else:
		print("InitializationManager: No 'themes' data found or invalid format in task_development.json")

	task_dev_state["strategies"] = {}
	if task_dev.has("strategies") and typeof(task_dev["strategies"]) == TYPE_DICTIONARY:
		for strategy_key in task_dev["strategies"]:
			var s_data = task_dev["strategies"][strategy_key]
			if typeof(s_data) == TYPE_DICTIONARY:
				task_dev_state["strategies"][strategy_key] = s_data.duplicate(true)
			else:
				printerr("InitializationManager: Invalid data format for strategy: ", strategy_key)
	else:
		print("InitializationManager: No 'strategies' data found or invalid format in task_development.json")

	if task_dev.has("product_focus_points") and typeof(task_dev["product_focus_points"]) == TYPE_DICTIONARY:
		task_dev_state["product_focus_points"] = task_dev["product_focus_points"].duplicate(true)
	else:
		print("InitializationManager: No 'product_focus_points' data found or invalid format in task_development.json")
		task_dev_state["product_focus_points"] = {}
	# --- END: task_dev_state 构建逻辑 ---

	# 4. 将包含所有任务开发状态的字典 task_dev_state 赋值给 initial_state 下的 "task_development" 键
	initial_state["task_development"] = task_dev_state

	# 5. NEW: 处理 NPC 数据，将其存入 initial_state 的 "npcs" 键下
	# npc_defs 是从 npc.json 加载的完整内容，结构为 {"npc": {"米子一": {...}, "塔奇": {...}}}
	# 我们希望将 {"米子一": {...}, "塔奇": {...}} 这部分存入 GameState
	if npc_defs.has("npc") and typeof(npc_defs["npc"]) == TYPE_DICTIONARY:
		initial_state["npcs"] = npc_defs["npc"].duplicate(true) # 深拷贝NPC数据
		print("InitializationManager: NPC data added to initial state under 'npcs' key.")
	else:
		# 如果 npc.json 结构不符合预期 (例如顶层没有 "npc" 键，或其值不是字典)
		# 打印错误，并为 "npcs" 设置一个空字典，以避免后续代码因键不存在而出错
		printerr("InitializationManager: 'npc' key not found or not a Dictionary in npc_initial_data from npc.json. Initializing 'npcs' as empty.")
		initial_state["npcs"] = {}

	print("InitializationManager: Initial game state built with 'task_development' and 'npcs' structure.")
	return initial_state
