"""Step definitions for Bug #7488 — sandbox_path auto-stored in checkpoint metadata.

These steps verify that create_checkpoint() automatically stores sandbox_path
in metadata from sandbox.context.sandbox_path, enabling rollback_to() to work
without the caller manually supplying sandbox_path in metadata.

Split from checkpoint_manager_coverage_steps.py to keep files under 500 lines.
"""

from __future__ import annotations

import os

from behave import given, then
from behave.runner import Context


def _register_cleanup(context: Context, path: str) -> None:
    """Schedule a directory for cleanup after the scenario."""
    if not hasattr(context, "_cleanup_handlers"):
        context._cleanup_handlers = []
    context._cleanup_handlers.append(
        lambda p=path: __import__("shutil").rmtree(p, ignore_errors=True)
    )


@then("the returned checkpoint metadata should contain the sandbox path")
def step_assert_metadata_has_sandbox_path(context: Context) -> None:
    """Verify that create_checkpoint() automatically stores sandbox_path in metadata."""
    cp = context.cp_result
    _register_cleanup(context, os.path.dirname(cp.snapshot_path))
    assert "sandbox_path" in cp.metadata, (
        "Expected 'sandbox_path' key in checkpoint metadata, but it was not found. "
        "Bug #7488: create_checkpoint() must store sandbox_path in metadata."
    )
    assert cp.metadata["sandbox_path"] == context.temp_sandbox, (
        f"Expected sandbox_path={context.temp_sandbox!r}, "
        f"got {cp.metadata['sandbox_path']!r}"
    )


@given(
    "a checkpoint was created for the temporary sandbox without explicit sandbox_path metadata"
)
def step_create_cp_for_temp_sandbox_no_explicit_path(context: Context) -> None:
    """Create a checkpoint without manually supplying sandbox_path in metadata.

    After the fix for bug #7488, create_checkpoint() should automatically
    store sandbox_path in metadata from sandbox.context.sandbox_path.
    """
    context.cp_result = context.mgr.create_checkpoint(
        sandbox=context.mock_sb,
        plan_id="plan-rb-autopath",
        phase="pre_execute",
        # Intentionally NOT passing sandbox_path in metadata — the fix should
        # auto-populate it from sandbox.context.sandbox_path.
    )
    _register_cleanup(context, os.path.dirname(context.cp_result.snapshot_path))
    context.crafted_cp = context.cp_result
