extends SceneTree
## Headless screenshot test — captures a viewport frame after the scene loads.
## Run:  godot --headless --script tests/screenshot_test.gd
##
## Outputs:  tests/output/screenshot.png
## Exit code 0 = success, 1 = failure.

const OUTPUT_DIR := "res://tests/output"
const SETTLE_TIME := 2.0  # seconds to let physics/animations settle


func _init() -> void:
	_run.call_deferred()


func _run() -> void:
	# Ensure output directory exists
	DirAccess.make_dir_recursive_absolute(OUTPUT_DIR)

	# Load and switch to the main scene
	var scene_res := load("res://scene.tscn")
	if scene_res == null:
		push_error("screenshot_test: Failed to load scene.tscn")
		quit(1)
		return

	var scene_instance: Node = scene_res.instantiate()
	root.add_child(scene_instance)

	# Wait for the scene to settle (physics, spawning, animations)
	await create_timer(SETTLE_TIME).timeout

	# Capture viewport
	var img: Image = root.get_viewport().get_texture().get_image()
	if img == null:
		push_error("screenshot_test: Failed to capture viewport image")
		quit(1)
		return

	var path := OUTPUT_DIR + "/screenshot.png"
	var err := img.save_png(path)
	if err != OK:
		push_error("screenshot_test: Failed to save PNG (error %d)" % err)
		quit(1)
		return

	print("screenshot_test: Saved %s (%dx%d)" % [path, img.get_width(), img.get_height()])
	quit(0)
