import hmac
import hashlib
import json
import pytest
from infrastructure.telegram.service import TelegramApiService
from modules.channels import (
    get_channel_registry,
    ChannelType,
    TelegramChannelAdapter,
    DiscordChannelAdapter,
    GenericWebhookChannelAdapter,
    ChannelMessageRequest,
    ChannelButton,
)


@pytest.mark.asyncio
async def test_channel_registry_resolution():
    registry = get_channel_registry()

    tg = registry.get_adapter(ChannelType.TELEGRAM, token="mock_tg_token")
    assert isinstance(tg, TelegramChannelAdapter)
    assert tg.channel_type == ChannelType.TELEGRAM

    disc = registry.get_adapter("discord", token="mock_disc_token")
    assert isinstance(disc, DiscordChannelAdapter)
    assert disc.channel_type == ChannelType.DISCORD

    wh = registry.get_adapter("webhook", secret="sec_123")
    assert isinstance(wh, GenericWebhookChannelAdapter)
    assert wh.channel_type == ChannelType.WEBHOOK


@pytest.mark.asyncio
async def test_telegram_channel_adapter_lifecycle():
    token = "mock_tg_channel_test"
    TelegramApiService.register_mock_bot(token=token, username="channel_test_bot", first_name="Channel Tester")

    adapter = TelegramChannelAdapter(bot_token=token)

    # 1. Send Message
    req = ChannelMessageRequest(
        recipient_id="987654321",
        text="<b>Astraea Super Cloud</b> Alert",
        parse_mode="HTML",
        buttons=[
            [
                ChannelButton(text="Open URL", action_type="url", value="https://example.com"),
                ChannelButton(text="Action Click", action_type="callback", value="act:verify"),
            ]
        ],
    )
    result = await adapter.send_message(req)
    assert result.success is True
    assert result.channel == ChannelType.TELEGRAM
    assert result.message_id is not None

    # 2. Webhook verification
    secret = "tg_webhook_super_secret"
    headers_valid = {"X-Telegram-Bot-Api-Secret-Token": secret}
    headers_invalid = {"X-Telegram-Bot-Api-Secret-Token": "wrong_secret"}
    assert await adapter.verify_webhook_signature(headers_valid, b"", secret) is True
    assert await adapter.verify_webhook_signature(headers_invalid, b"", secret) is False

    # 3. Payload Normalization
    raw_msg = {
        "update_id": 1001,
        "message": {
            "message_id": 42,
            "from": {"id": 12345, "first_name": "John", "last_name": "Doe", "username": "johndoe"},
            "chat": {"id": 12345, "type": "private"},
            "text": "Hello Astraea Bot",
            "date": 1700000000,
        },
    }
    normalized = await adapter.normalize_incoming_event(raw_msg)
    assert normalized["event_type"] == "message"
    assert normalized["sender_id"] == "12345"
    assert normalized["sender_name"] == "John Doe"
    assert normalized["text"] == "Hello Astraea Bot"
    assert normalized["chat_id"] == "12345"


@pytest.mark.asyncio
async def test_discord_channel_adapter_normalization():
    adapter = DiscordChannelAdapter()

    # Discord interaction payload
    interaction_payload = {
        "id": "int_999",
        "type": 2,
        "channel_id": "chan_456",
        "member": {
            "user": {"id": "usr_888", "username": "astraea_pilot"}
        },
        "data": {
            "name": "help_command",
            "custom_id": "btn_confirm",
        },
    }

    norm = await adapter.normalize_incoming_event(interaction_payload)
    assert norm["event_type"] == "interaction"
    assert norm["sender_id"] == "usr_888"
    assert norm["sender_name"] == "astraea_pilot"
    assert norm["chat_id"] == "chan_456"
    assert norm["callback_data"] == "btn_confirm"


@pytest.mark.asyncio
async def test_generic_webhook_hmac_and_normalization():
    secret = "wh_top_secret_hmac_key"
    adapter = GenericWebhookChannelAdapter(secret=secret)

    # Webhook signature verification
    body = b'{"event":"order.placed","user_id":"cust_777","amount":49.99}'
    sig = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    headers = {"X-Hub-Signature-256": f"sha256={sig}"}

    assert await adapter.verify_webhook_signature(headers, body, secret) is True
    assert await adapter.verify_webhook_signature(headers, body, "wrong_key") is False

    # Webhook payload normalization
    parsed_json = json.loads(body.decode())
    norm = await adapter.normalize_incoming_event(parsed_json)
    assert norm["event_type"] == "order.placed"
    assert norm["sender_id"] == "cust_777"
    assert norm["channel"] == "webhook"
