"""Tests for the send_telegram skill."""

import os
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from fliiq.runtime.package_data import bundled_skills_dir
from fliiq.runtime.skills.base import SkillBase

SKILLS_DIR = str(bundled_skills_dir())


def _load_skill() -> SkillBase:
    return SkillBase(os.path.join(SKILLS_DIR, "send_telegram"))


def test_send_telegram_schema():
    skill = _load_skill()
    schema = skill.schema()
    assert schema["name"] == "send_telegram"
    assert "chat_id" in schema["parameters"]["properties"]
    assert "text" in schema["parameters"]["properties"]
    assert set(schema["parameters"]["required"]) == {"chat_id", "text"}


async def test_send_telegram_missing_token(monkeypatch):
    monkeypatch.delenv("TELEGRAM_BOT_TOKEN", raising=False)
    skill = _load_skill()
    with pytest.raises(ValueError, match="TELEGRAM_BOT_TOKEN"):
        await skill.execute({"chat_id": "123", "text": "Hello"})


async def test_send_telegram_success(monkeypatch):
    monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "fake-token")
    skill = _load_skill()

    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "ok": True,
        "result": {"message_id": 42},
    }

    with patch("httpx.AsyncClient") as mock_client_cls:
        mock_client = AsyncMock()
        mock_client.post.return_value = mock_response
        mock_client_cls.return_value.__aenter__ = AsyncMock(return_value=mock_client)
        mock_client_cls.return_value.__aexit__ = AsyncMock(return_value=False)
        result = await skill.execute({"chat_id": "123", "text": "Hello"})

    assert "sent" in result["status"].lower()
    assert result["message_id"] == 42


async def test_send_telegram_api_error(monkeypatch):
    monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "fake-token")
    skill = _load_skill()

    mock_response = MagicMock()
    mock_response.status_code = 400
    mock_response.json.return_value = {"description": "Bad Request: chat not found"}
    mock_response.text = "Bad Request: chat not found"

    with patch("httpx.AsyncClient") as mock_client_cls:
        mock_client = AsyncMock()
        mock_client.post.return_value = mock_response
        mock_client_cls.return_value.__aenter__ = AsyncMock(return_value=mock_client)
        mock_client_cls.return_value.__aexit__ = AsyncMock(return_value=False)
        with pytest.raises(ValueError, match="Telegram API error"):
            await skill.execute({"chat_id": "123", "text": "Hello"})
