from __future__ import annotations

import importlib.util
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
MODULE_PATH = REPO_ROOT / "tests" / "run_yaml_scenario.py"


def load_module():
    spec = importlib.util.spec_from_file_location("run_yaml_scenario", MODULE_PATH)
    assert spec is not None
    assert spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


runner = load_module()


def test_render_template_substitutes_variables():
    rendered = runner.render_template("hello {{name}} from {{place}}", {"name": "agent", "place": "sandbox"})
    assert rendered == "hello agent from sandbox"


def test_resolve_mapping_handles_dependency_order():
    resolved = runner.resolve_mapping(
        {
            "root": "/tmp/demo",
            "child": "{{root}}/child",
            "grandchild": "{{child}}/leaf",
        },
        {},
    )
    assert resolved["grandchild"] == "/tmp/demo/child/leaf"


def test_collect_inspect_paths_deduplicates_targets():
    step = {
        "inspect": ["/tmp/a"],
        "mkdirs": ["/tmp/a", "/tmp/b"],
        "assert_files": ["/tmp/b", "/tmp/c"],
    }
    result = runner.collect_inspect_paths(step, {})
    assert result == ["/tmp/a", "/tmp/b", "/tmp/c"]


def test_format_duration_uses_human_scales():
    assert runner.format_duration(0.25) == "250ms"
    assert runner.format_duration(2.5) == "2.50s"
    assert runner.format_duration(61.5) == "1m 1.50s"

