"""dispatch.py _patch_timer_metadata의 task_file 필드 패치 검증 (task-1995)."""
import json
import tempfile
from pathlib import Path
from unittest.mock import patch



def test_patch_timer_metadata_adds_task_file():
    """_patch_timer_metadata가 task_file 필드를 정상 기록하는지 검증."""
    import sys
    sys.path.insert(0, "/home/jay/workspace")
    from dispatch import _patch_timer_metadata

    with tempfile.TemporaryDirectory() as tmpdir:
        initial_data = {
            "tasks": {
                "task-test-1995": {
                    "status": "running",
                    "start_time": "2026-04-20T00:00:00"
                }
            }
        }

        workspace_root = Path(tmpdir) / "workspace"
        workspace_root.mkdir()
        memory_path = workspace_root / "memory"
        memory_path.mkdir()
        timer_path = memory_path / "task-timers.json"
        timer_path.write_text(json.dumps(initial_data), encoding="utf-8")

        with patch("dispatch.WORKSPACE", workspace_root):
            _patch_timer_metadata("task-test-1995", task_file="memory/tasks/task-test-1995.md")

        result = json.loads(timer_path.read_text(encoding="utf-8"))
        assert result["tasks"]["task-test-1995"]["task_file"] == "memory/tasks/task-test-1995.md"


def test_patch_timer_metadata_preserves_existing_fields():
    """task_file 패치 시 기존 필드가 보존되는지 검증."""
    import sys
    sys.path.insert(0, "/home/jay/workspace")
    from dispatch import _patch_timer_metadata

    with tempfile.TemporaryDirectory() as tmpdir:
        workspace_root = Path(tmpdir) / "workspace"
        workspace_root.mkdir()
        memory_path = workspace_root / "memory"
        memory_path.mkdir()
        timer_path = memory_path / "task-timers.json"

        initial_data = {
            "tasks": {
                "task-test-1995b": {
                    "status": "running",
                    "schedule_id": "sched-123",
                    "retry_count": 0,
                    "max_retry": 2,
                }
            }
        }
        timer_path.write_text(json.dumps(initial_data), encoding="utf-8")

        with patch("dispatch.WORKSPACE", workspace_root):
            _patch_timer_metadata("task-test-1995b", task_file="memory/tasks/task-test-1995b.md")

        result = json.loads(timer_path.read_text(encoding="utf-8"))
        entry = result["tasks"]["task-test-1995b"]
        # 기존 필드 보존 확인
        assert entry["schedule_id"] == "sched-123"
        assert entry["retry_count"] == 0
        assert entry["max_retry"] == 2
        # 새 필드 추가 확인
        assert entry["task_file"] == "memory/tasks/task-test-1995b.md"
