"""Component tests for workflow/session persistence lifecycle."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from cascade_fm.api import CascadeAPI


@pytest.mark.component
def test_workflow_roundtrip_persistence(tmp_path: Path) -> None:
    """Saved workflow should roundtrip through disk and restore identical payload."""
    api = CascadeAPI(workflow_dir=tmp_path)
    pipeline = {
        "id": "pipeline-component",
        "panes": [
            {"id": "pane_1", "operation": "filter_extension", "params": {"extensions": [".jpg"]}},
            {"id": "pane_2", "operation": "save_to", "params": {"target_dir": "/tmp/out"}},
        ],
    }

    assert api.save_workflow("release-roundtrip", pipeline) is True

    loaded = api.load_workflow("release-roundtrip")
    assert loaded == pipeline


@pytest.mark.component
def test_last_session_lifecycle_save_age_delete(tmp_path: Path) -> None:
    """Last-session snapshot supports save, age query, and deletion lifecycle."""
    api = CascadeAPI(workflow_dir=tmp_path)
    snapshot = {
        "id": "session",
        "panes": [{"id": "pane_1", "operation": "rename_pattern", "params": {"pattern": "{name}"}}],
    }

    assert api.save_workflow("__last_session__", snapshot) is True

    workflow_path = tmp_path / "last_session.json"
    assert workflow_path.exists()

    age = api.get_workflow_age_seconds("__last_session__")
    assert age is not None
    assert age >= 0.0

    payload = json.loads(workflow_path.read_text(encoding="utf-8"))
    assert payload["pipeline"] == snapshot

    assert api.delete_workflow("__last_session__") is True
    assert not workflow_path.exists()
