"""Tests for Telegram integration."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import pytest


# ── send_telegram ──────────────────────────────────────────────────────────


class TestSendTelegram:
    """Test the send_telegram function."""

    @patch("alive.integrations.telegram._load_config", return_value={})
    def test_raises_when_not_configured(self, mock_cfg):
        from alive.integrations.telegram import send_telegram

        with pytest.raises(ValueError, match="not configured"):
            send_telegram("Hello")

    @patch("alive.integrations.telegram._load_config", return_value={"telegram_token": "tok", "telegram_chat_id": "123"})
    def test_sends_message_successfully(self, mock_cfg):
        from alive.integrations.telegram import send_telegram

        mock_resp = MagicMock()
        mock_resp.json.return_value = {"ok": True}
        mock_resp.raise_for_status = MagicMock()

        with patch("httpx.post", return_value=mock_resp) as mock_post:
            result = send_telegram("Test message")

        assert result is True
        mock_post.assert_called_once()
        call_args = mock_post.call_args
        assert "sendMessage" in call_args[0][0]
        assert call_args[1]["json"]["text"] == "Test message"

    @patch("alive.integrations.telegram._load_config", return_value={"telegram_token": "tok", "telegram_chat_id": "123"})
    def test_truncates_long_messages(self, mock_cfg):
        from alive.integrations.telegram import send_telegram

        mock_resp = MagicMock()
        mock_resp.json.return_value = {"ok": True}
        mock_resp.raise_for_status = MagicMock()

        long_msg = "x" * 5000
        with patch("httpx.post", return_value=mock_resp) as mock_post:
            send_telegram(long_msg)

        sent_text = mock_post.call_args[1]["json"]["text"]
        assert len(sent_text) <= 4100  # 4000 + truncation message


# ── send_telegram_photo ────────────────────────────────────────────────────


class TestSendTelegramPhoto:
    """Test the send_telegram_photo function."""

    @patch("alive.integrations.telegram._load_config", return_value={})
    def test_raises_when_not_configured(self, mock_cfg):
        from alive.integrations.telegram import send_telegram_photo

        with pytest.raises(ValueError, match="not configured"):
            send_telegram_photo("/tmp/test.png")

    @patch("alive.integrations.telegram._load_config", return_value={"telegram_token": "tok", "telegram_chat_id": "123"})
    def test_sends_photo(self, mock_cfg, tmp_path):
        from alive.integrations.telegram import send_telegram_photo

        # Create a fake image file
        img = tmp_path / "test.png"
        img.write_bytes(b"fake png data")

        mock_resp = MagicMock()
        mock_resp.json.return_value = {"ok": True}
        mock_resp.raise_for_status = MagicMock()

        with patch("httpx.post", return_value=mock_resp) as mock_post:
            result = send_telegram_photo(str(img), caption="Test caption")

        assert result is True
        assert "sendPhoto" in mock_post.call_args[0][0]


# ── send_telegram_file ─────────────────────────────────────────────────────


class TestSendTelegramFile:
    """Test the send_telegram_file function."""

    @patch("alive.integrations.telegram._load_config", return_value={"telegram_token": "tok", "telegram_chat_id": "123"})
    def test_sends_file(self, mock_cfg, tmp_path):
        from alive.integrations.telegram import send_telegram_file

        doc = tmp_path / "data.csv"
        doc.write_text("col1,col2\n1,2\n")

        mock_resp = MagicMock()
        mock_resp.json.return_value = {"ok": True}
        mock_resp.raise_for_status = MagicMock()

        with patch("httpx.post", return_value=mock_resp) as mock_post:
            result = send_telegram_file(str(doc), caption="Data")

        assert result is True
        assert "sendDocument" in mock_post.call_args[0][0]


# ── _get_bot_name ──────────────────────────────────────────────────────────


class TestGetBotName:
    """Test bot name fetching."""

    def test_returns_username(self):
        from alive.integrations.telegram import _get_bot_name

        mock_resp = MagicMock()
        mock_resp.json.return_value = {"ok": True, "result": {"username": "test_bot"}}
        mock_resp.raise_for_status = MagicMock()

        with patch("httpx.get", return_value=mock_resp):
            name = _get_bot_name("fake-token")

        assert name == "@test_bot"

    def test_returns_none_on_error(self):
        from alive.integrations.telegram import _get_bot_name

        with patch("httpx.get", side_effect=Exception("network error")):
            name = _get_bot_name("bad-token")

        assert name is None


# ── telegram_status ────────────────────────────────────────────────────────


class TestTelegramStatus:
    """Test telegram_status function."""

    @patch("alive.integrations.telegram._load_config", return_value={})
    def test_not_configured(self, mock_cfg):
        from alive.integrations.telegram import telegram_status

        status = telegram_status()
        assert status["configured"] is False
        assert status["token_set"] is False

    @patch("alive.integrations.telegram._load_config", return_value={"telegram_token": "tok", "telegram_chat_id": "123"})
    @patch("alive.integrations.telegram._get_bot_name", return_value="@mybot")
    def test_configured(self, mock_name, mock_cfg):
        from alive.integrations.telegram import telegram_status

        status = telegram_status()
        assert status["configured"] is True
        assert status["bot_name"] == "@mybot"


# ── stop_telegram_bot ──────────────────────────────────────────────────────


class TestStopTelegramBot:
    """Test stopping the bot daemon."""

    def test_returns_false_when_no_pid_file(self, tmp_path):
        from alive.integrations.telegram import stop_telegram_bot

        with patch("alive.config.ALIVE_HOME", tmp_path):
            result = stop_telegram_bot()

        assert result is False
