extends ConditionLeaf

func is_goals_achieved(actor) -> bool:
	# Convert goals to 2D for easier pattern matching
	var goals_2d = []
	for i in range(3):
		var row = []
		for j in range(3):
			row.append(actor.goals[i * 3 + j])
		goals_2d.append(row)
		
	# Convert playerboard to 2D
	var board_2d = []
	for i in range(5):
		var row = []
		for j in range(5):
			row.append(actor.playerboard[i * 5 + j])
		board_2d.append(row)
	
	# Check every possible 3x3 region in the 5x5 board
	for start_row in range(3):
		for start_col in range(3):
			var matches = true
			for i in range(3):
				for j in range(3):
					var board_item = board_2d[start_row + i][start_col + j]
					var goal_item = goals_2d[i][j]
					
					if goal_item != -1 and goal_item != board_item:
						matches = false
						break
					elif goal_item == -1 and board_item != -1:
						matches = false
						break
				if not matches:
					break
			if matches:
				return true
	return false

func tick(actor: Node, blackboard: Blackboard) -> int:
	# First check if goals are achieved
	if is_goals_achieved(actor):
		blackboard.set_value("current_action", "idle")
		return FAILURE
		
	if actor.playerboard_is_full():
		return FAILURE
		
	# Check current position
	var current_cell = Vector3i(actor.current_position.x, 1, actor.current_position.y)
	var item = actor.enhanced_gridmap.get_cell_item(current_cell)
	if item in actor.goals:
		blackboard.set_value("grab_position", actor.current_position)
		return SUCCESS
		
	# Check adjacent cells
	var neighbors = actor.enhanced_gridmap.get_neighbors(actor.current_position, 0)
	for neighbor in neighbors:
		if not neighbor.is_walkable:
			continue
		var cell = Vector3i(neighbor.position.x, 1, neighbor.position.y)
		item = actor.enhanced_gridmap.get_cell_item(cell)
		if item in actor.goals:
			blackboard.set_value("grab_position", neighbor.position)
			return SUCCESS
	
	return FAILURE
