extends SceneTree
var done := false
var shots := {}
var out_dir := ""

func _initialize() -> void:
    call_deferred("_run")

func _exercise(probe: Node, authored: Dictionary) -> void:
    await probe.call("_victory", 0, authored, false)
    done = true

func _run() -> void:
    var expected := OS.get_environment("BIGEGG_DEV_RUN_DIR").replace("\\", "/")
    if expected.is_empty() or not OS.get_user_data_dir().replace("\\", "/").begins_with(expected + "/"):
        push_error("CAPTURE ISOLATION FAILED")
        quit(2)
        return
    out_dir = OS.get_cmdline_user_args()[0]
    await process_frame
    var state: Node = root.get_node("GameState")
    state.set("save_locked", true)
    var catalog: Script = load("res://scripts/core/data_catalog.gd")
    var authored: Dictionary = catalog.get("STORY_TRIGGERS").duplicate(true)
    var probe := Node.new()
    probe.set_script(load("res://scripts/core/dimension_finale_check.gd"))
    probe.set("is_probe", true)
    probe.process_mode = Node.PROCESS_MODE_ALWAYS
    root.add_child(probe)
    _exercise(probe, authored)
    var start := Time.get_ticks_msec()
    while not done and Time.get_ticks_msec() - start < 30000:
        await process_frame
        var figures := get_nodes_in_group("story_rift")
        if figures.is_empty():
            continue
        var snapshot: Dictionary = figures[0].call("presentation")
        var phase := str(snapshot.phase)
        var name := ""
        if phase == "emerge" and float(snapshot.entity_elevation) > 84:
            name = "01-emergence"
        elif phase == "open" and float(snapshot.opening) > 0.99:
            name = "02-faille"
        elif phase == "escape" and float(snapshot.entity_scale) < 0.55 and float(snapshot.entity_scale) > 0.3:
            name = "03-fuite"
        elif phase == "follow" and figures[0].get("hero").global_position.distance_to(snapshot.portal_position) < 140.0:
            name = "04-poursuite"
        if not name.is_empty() and not shots.has(name):
            shots[name] = true
            await RenderingServer.frame_post_draw
            root.get_viewport().get_texture().get_image().save_png(out_dir.path_join(name + ".png"))
            print("CAPTURED ", name)
    await create_timer(0.5).timeout
    await RenderingServer.frame_post_draw
    root.get_viewport().get_texture().get_image().save_png(out_dir.path_join("05-restaurant.png"))
    print("CAPTURED 05-restaurant; failures=", probe.get("failures"))
    Input.set_custom_mouse_cursor(null)
    change_scene_to_file("res://scenes/main/main_menu.tscn")
    for frame in 8:
        await process_frame
    probe.queue_free()
    var audio: Node = root.get_node("AudioDirector")
    audio.call("shutdown")
    quit(0 if done and int(probe.get("failures")) == 0 else 1)
