from types import SimpleNamespace

from progress_events import PROGRESS_CHANNEL, publish_progress_event, task_progress_payload


def test_task_progress_payload_uses_dashboard_task_id_and_project_name():
    task = SimpleNamespace(
        id=12,
        project_id=7,
        project=SimpleNamespace(name="demo.mp4"),
        status="success",
        progress=100,
        message="解析完成",
        error=None,
        updated_at=None,
    )

    payload = task_progress_payload(task)

    assert payload["type"] == "complete"
    assert payload["taskId"] == "task-12"
    assert payload["task_id"] == 12
    assert payload["project_id"] == 7
    assert payload["filename"] == "demo.mp4"
    assert payload["projectName"] == "demo.mp4"
    assert payload["status"] == "解析完成"


def test_task_progress_payload_marks_cancelled_tasks():
    task = SimpleNamespace(
        id=13,
        project_id=7,
        project=SimpleNamespace(name="demo.mp4"),
        status="cancelled",
        progress=100,
        message="任务已取消",
        error="Cancelled by user",
        updated_at=None,
    )

    payload = task_progress_payload(task)

    assert payload["type"] == "cancelled"
    assert payload["status"] == "任务已取消"
    assert payload["error"] == "Cancelled by user"


def test_publish_progress_event_writes_json_to_redis(monkeypatch):
    calls = []

    class FakeRedis:
        def publish(self, channel, payload):
            calls.append((channel, payload))

    monkeypatch.setattr("progress_events.get_redis_client", lambda: FakeRedis())

    publish_progress_event({"type": "progress", "message": "正在下载媒体文件"})

    assert calls
    assert calls[0][0] == PROGRESS_CHANNEL
    assert "正在下载媒体文件" in calls[0][1]
