"""
통합 테스트: dispatch.py - _check_affected_files_overlap, _send_overlap_telegram_warning
task-1837_5.1 - 엔키 작성
"""

import json
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

sys.path.insert(0, "/home/jay/workspace")


def _write_timers(tmp_path: Path, data: dict) -> None:
    """task-timers.json을 tmp_path/memory/ 에 작성."""
    memory = tmp_path / "memory"
    memory.mkdir(parents=True, exist_ok=True)
    (memory / "task-timers.json").write_text(json.dumps(data), encoding="utf-8")


# ── _check_affected_files_overlap ───────────────────────────────────────────

def test_overlap_no_running_tasks_returns_empty(tmp_path, monkeypatch):
    """running 상태 task가 없으면 빈 리스트를 반환해야 한다."""
    data = {
        "tasks": {
            "task-100": {"status": "done", "affected_files": ["dispatch.py"]},
        }
    }
    _write_timers(tmp_path, data)

    import dispatch as _d
    monkeypatch.setattr(_d, "WORKSPACE", tmp_path)

    result = _d._check_affected_files_overlap(["dispatch.py"], "task-200")
    assert result == []


def test_overlap_running_task_with_same_file_returns_warning(tmp_path, monkeypatch):
    """running 상태 task와 affected_files가 겹치면 경고 메시지 리스트를 반환해야 한다."""
    data = {
        "tasks": {
            "task-101": {
                "status": "running",
                "affected_files": ["dispatch.py", "utils/logger.py"],
            }
        }
    }
    _write_timers(tmp_path, data)

    import dispatch as _d
    monkeypatch.setattr(_d, "WORKSPACE", tmp_path)

    warnings = _d._check_affected_files_overlap(["dispatch.py", "server.py"], "task-202")
    assert len(warnings) == 1
    assert "task-101" in warnings[0]
    assert "dispatch.py" in warnings[0]


def test_overlap_excludes_current_task_id(tmp_path, monkeypatch):
    """자기 자신(current_task_id)은 겹침 검사에서 제외되어야 한다."""
    data = {
        "tasks": {
            "task-999": {
                "status": "running",
                "affected_files": ["dispatch.py"],
            }
        }
    }
    _write_timers(tmp_path, data)

    import dispatch as _d
    monkeypatch.setattr(_d, "WORKSPACE", tmp_path)

    # current_task_id == "task-999" → 자기 자신이므로 제외
    result = _d._check_affected_files_overlap(["dispatch.py"], "task-999")
    assert result == []


def test_overlap_no_timers_file_returns_empty(tmp_path, monkeypatch):
    """task-timers.json이 없으면 빈 리스트를 반환해야 한다."""
    # memory 디렉토리만 만들고 파일은 만들지 않음
    (tmp_path / "memory").mkdir(parents=True, exist_ok=True)

    import dispatch as _d
    monkeypatch.setattr(_d, "WORKSPACE", tmp_path)

    result = _d._check_affected_files_overlap(["any_file.py"], "task-300")
    assert result == []


def test_overlap_multiple_running_tasks(tmp_path, monkeypatch):
    """여러 running task 중 겹치는 것만 경고에 포함되어야 한다."""
    data = {
        "tasks": {
            "task-110": {
                "status": "running",
                "affected_files": ["a.py"],
            },
            "task-111": {
                "status": "running",
                "affected_files": ["b.py"],
            },
            "task-112": {
                "status": "done",
                "affected_files": ["a.py", "b.py"],
            },
        }
    }
    _write_timers(tmp_path, data)

    import dispatch as _d
    monkeypatch.setattr(_d, "WORKSPACE", tmp_path)

    warnings = _d._check_affected_files_overlap(["a.py"], "task-500")
    assert len(warnings) == 1
    assert "task-110" in warnings[0]
    assert "task-111" not in warnings[0]


# ── _send_overlap_telegram_warning ──────────────────────────────────────────

def test_send_overlap_warning_empty_list_does_not_call_urlopen():
    """warnings가 비어있으면 urllib.request.urlopen을 호출하지 않아야 한다."""
    import dispatch as _d

    with patch("urllib.request.urlopen") as mock_urlopen:
        _d._send_overlap_telegram_warning([])
        mock_urlopen.assert_not_called()


def test_send_overlap_warning_no_bot_token_skips(monkeypatch):
    """ANU_BOT_TOKEN이 설정되지 않으면 Telegram 호출을 스킵해야 한다."""
    import dispatch as _d

    monkeypatch.delenv("ANU_BOT_TOKEN", raising=False)

    with patch("urllib.request.urlopen") as mock_urlopen:
        _d._send_overlap_telegram_warning(["[파일 충돌 경고] task-101(running)와 파일 겹침: dispatch.py"])
        mock_urlopen.assert_not_called()


def test_send_overlap_warning_with_token_calls_urlopen(monkeypatch):
    """ANU_BOT_TOKEN이 있으면 urlopen을 호출해야 한다."""
    import dispatch as _d

    monkeypatch.setenv("ANU_BOT_TOKEN", "test-token-123")

    mock_resp = MagicMock()
    with patch("urllib.request.urlopen", return_value=mock_resp) as mock_urlopen:
        _d._send_overlap_telegram_warning(["[파일 충돌 경고] task-101(running)와 파일 겹침: dispatch.py"])
        mock_urlopen.assert_called_once()
