extends SceneTree

var output := ""

func _initialize() -> void:
	call_deferred("_run")

func _run() -> void:
	output = OS.get_cmdline_user_args()[0]
	for frame: int in 5:
		await process_frame
	var state := root.get_node("GameState")
	state.set("save_locked", true)
	state.call("set_scoped_value", "run", "room_id", "d1_l05_lower_docks")
	state.call("set_scoped_value", "run", "level", 5)
	var dungeon: Node2D = load("res://scenes/dungeon/dungeon.tscn").instantiate()
	root.add_child(dungeon)
	current_scene = dungeon
	for frame: int in 20:
		await process_frame
	paused = false
	dungeon.call("_clear_room_contents")
	var player: Node2D = dungeon.get("player")
	player.set("invulnerability", 999.0)
	player.set_physics_process(false)
	player.global_position = Vector2(960, 780)
	var gull: CharacterBody2D = load("res://scenes/enemies/enemy.tscn").instantiate()
	dungeon.add_child(gull)
	gull.call("setup", "powder_gull")
	gull.set_physics_process(false)
	gull.global_position = Vector2(880, 700)
	gull.set("look_direction", Vector2.RIGHT)
	gull.set("visual_height", 35.0)
	for frame: int in 12:
		await process_frame
	await _move(gull, Vector2(320, 0), "gull_right")
	await _move(gull, Vector2(-320, 0), "gull_retreat")
	await _move(gull, Vector2.ZERO, "gull_stopped")
	var bridge := root.get_node("Bridge3D")
	var avatar: Node3D = bridge.get("_avatars").get(gull)
	var lines := avatar.get_node("SpeedLines")
	assert(lines.get_children().all(func(line: Node): return not line.visible))
	gull.set("active", false)
	await _move(gull, Vector2(320, 0), "gull_dead")
	assert(lines.get_children().all(func(line: Node): return not line.visible))
	gull.queue_free()
	await process_frame
	var brute: CharacterBody2D = load("res://scenes/enemies/enemy.tscn").instantiate()
	dungeon.add_child(brute)
	brute.call("setup", "barnacle_brute")
	brute.set_physics_process(false)
	brute.global_position = Vector2(960, 650)
	brute.set("look_direction", Vector2.DOWN)
	await _move(brute, Vector2.ZERO, "brute_idle")
	await _move(brute, Vector2(120, 0), "brute_walk")
	root.get_node("AudioDirector").call("shutdown")
	for frame: int in 16:
		await process_frame
	print("ENEMY CAPTURES OK")
	quit()

func _move(beast: CharacterBody2D, motion: Vector2, label: String) -> void:
	for frame: int in 18:
		await physics_frame
		beast.velocity = motion
		beast.move_and_slide()
		await process_frame
	var bridge := root.get_node("Bridge3D")
	var avatar: Node3D = bridge.get("_avatars").get(beast)
	if beast.get("enemy_id") == "powder_gull" and motion != Vector2.ZERO and beast.get("active"):
		assert(avatar.get_node("SpeedLines").get_children().any(func(line: Node): return line.visible))
	root.get_viewport().get_texture().get_image().save_png(output.path_join(label + ".png"))
	print("CAPTURE ", label, " ACTUAL MOTION ", beast.get_real_velocity())
