import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import hash_webhook_secret
from modules.bots.models import Bot, BotCredential, BotWebhook, BotSetting
from modules.identity.models import User
from modules.tenants.models import Tenant, TenantMember
from core.encryption import encrypt_string


@pytest.mark.asyncio
async def test_bot_modular_api_and_execution_lifecycle(
    async_client: AsyncClient,
    db_session: AsyncSession,
):
    # --------------------------------------------------------------------------
    # 1. Setup Tenant, User, and Bot
    # --------------------------------------------------------------------------
    user_email = f"mod_dev_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_email, "password": "PasswordM123!", "full_name": "Modular Dev"},
    )
    user_token = reg_resp.json()["data"]["access_token"]

    tenant_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {user_token}"},
        json={"name": "Modular Fleet Org", "slug": f"mod-{uuid.uuid4().hex[:6]}"},
    )
    tenant_id = uuid.UUID(tenant_resp.json()["data"]["id"])
    headers = {
        "Authorization": f"Bearer {user_token}",
        "X-Tenant-ID": str(tenant_id),
    }

    # Register Bot
    bot_token = f"token_modular_{uuid.uuid4().hex[:8]}_test"
    bot_username = f"modular_bot_{uuid.uuid4().hex[:6]}"
    TelegramApiService.register_mock_bot(bot_token, bot_username, "Modular Bot")

    bot_reg_resp = await async_client.post(
        "/api/v1/bots",
        headers=headers,
        json={"token": bot_token, "name": "Nexus Modular Bot", "default_locale": "en"},
    )
    assert bot_reg_resp.status_code == 201
    bot_data = bot_reg_resp.json()["data"]
    bot_id = uuid.UUID(bot_data["id"])

    # --------------------------------------------------------------------------
    # 2. Query Bot Modules API: GET /api/v1/bots/{bot_id}/modules
    # --------------------------------------------------------------------------
    modules_resp = await async_client.get(f"/api/v1/bots/{bot_id}/modules", headers=headers)
    assert modules_resp.status_code == 200
    mods = modules_resp.json()["data"]
    assert len(mods) == 18
    assert "redeem_codes" in [m["id"] for m in mods]
    assert "captcha_gate" in [m["id"] for m in mods]
    assert "daily_rewards" in [m["id"] for m in mods]
    assert "file_store" in [m["id"] for m in mods]

    mod_map = {m["id"]: m for m in mods}
    # Auto-provisioned foundational modules should be active
    assert mod_map["welcome_message"]["is_enabled"] is True
    assert mod_map["broadcasts"]["is_enabled"] is True
    # Others installed on-demand
    assert mod_map["referrals"]["is_enabled"] is False

    # --------------------------------------------------------------------------
    # 3. Install & Toggle Modules via API
    # --------------------------------------------------------------------------
    # Activate Referrals
    toggle_ref = await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/referrals/toggle",
        headers=headers,
        json={"is_enabled": True},
    )
    assert toggle_ref.status_code == 200
    assert toggle_ref.json()["data"]["is_enabled"] is True

    # Activate Subscriptions
    toggle_sub = await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/subscriptions/toggle",
        headers=headers,
        json={"is_enabled": True},
    )
    assert toggle_sub.status_code == 200
    assert toggle_sub.json()["data"]["is_enabled"] is True

    # Update Auto Filter Config & Toggle
    cfg_resp = await async_client.patch(
        f"/api/v1/bots/{bot_id}/modules/auto_filter/config",
        headers=headers,
        json={
            "config": {
                "rules": [{"trigger": "catalog", "match_type": "contains", "response": "📦 120 Products Available in Store."}],
                "blocked_words": ["malware"],
                "action_on_blocked": "warn",
            }
        },
    )
    assert cfg_resp.status_code == 200
    await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/auto_filter/toggle",
        headers=headers,
        json={"is_enabled": True},
    )

    # --------------------------------------------------------------------------
    # 4. Verify Real Webhook Execution Against Modules
    # --------------------------------------------------------------------------
    TelegramApiService.clear_sent_messages()

    # Query bot secret token to sign webhook requests
    bot_obj = await db_session.get(Bot, bot_id)
    webhook_obj = bot_obj.webhook
    # Use mock matching token
    secret_token = "valid_secret_for_webhook"
    webhook_obj.secret_hash = hash_webhook_secret(secret_token)
    await db_session.commit()

    webhook_headers = {"X-Telegram-Bot-Api-Secret-Token": secret_token}

    # 4.1 Test /referral command with Referrals active
    resp_ref = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10001,
            "message": {
                "from": {"id": 555111, "username": "testuser1"},
                "chat": {"id": 555111},
                "text": "/referral",
            },
        },
    )
    assert resp_ref.status_code == 200
    sent = TelegramApiService.get_sent_messages()
    assert len(sent) >= 1
    assert "Your Referral Portal" in sent[-1]["text"]

    # 4.2 Toggle Referrals OFF and verify execution is blocked!
    await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/referrals/toggle",
        headers=headers,
        json={"is_enabled": False},
    )
    resp_ref_off = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10002,
            "message": {
                "from": {"id": 555111, "username": "testuser1"},
                "chat": {"id": 555111},
                "text": "/referral",
            },
        },
    )
    assert resp_ref_off.status_code == 200
    sent_off = TelegramApiService.get_sent_messages()
    assert "The Referral Program is currently deactivated" in sent_off[-1]["text"]

    # 4.3 Test Auto-Filter keyword rule execution
    resp_filter = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10003,
            "message": {
                "from": {"id": 555111, "username": "testuser1"},
                "chat": {"id": 555111},
                "text": "Please show me the catalog items",
            },
        },
    )
    assert resp_filter.status_code == 200
    assert resp_filter.json().get("auto_filtered") is True
    sent_filter = TelegramApiService.get_sent_messages()
    assert "120 Products Available in Store" in sent_filter[-1]["text"]

    # 4.4 Test Subscriptions /plans command
    resp_sub = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10004,
            "message": {
                "from": {"id": 555111, "username": "testuser1"},
                "chat": {"id": 555111},
                "text": "/plans",
            },
        },
    )
    assert resp_sub.status_code == 200
    sent_sub = TelegramApiService.get_sent_messages()
    assert "VIP Subscription Tiers" in sent_sub[-1]["text"]

    # 4.5 Test Admin Verification Endpoint
    verify_resp = await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/verify-admin",
        headers=headers,
        json={"chat_id": "-1002345678901", "module_id": "force_join"},
    )
    assert verify_resp.status_code == 200
    verify_data = verify_resp.json()["data"]
    assert verify_data["is_admin"] is True
    assert verify_data["can_post_messages"] is True

    # --------------------------------------------------------------------------
    # 5. Redeem Codes & 3-Way Trigger Control Endpoints & Execution
    # --------------------------------------------------------------------------
    # 5.1 Enable redeem_codes module
    await async_client.post(
        f"/api/v1/bots/{bot_id}/modules/redeem_codes/toggle",
        headers=headers,
        json={"is_enabled": True},
    )

    # 5.2 Create a redeem code via API
    create_rc = await async_client.post(
        f"/api/v1/bots/{bot_id}/redeem-codes",
        headers=headers,
        json={
            "code": "PROMO2026",
            "title": "Welcome Gift Voucher",
            "reward_type": "subscription_days",
            "reward_value": 7,
            "max_uses": 5,
        },
    )
    assert create_rc.status_code == 201
    rc_data = create_rc.json()["data"]
    assert rc_data["code"] == "PROMO2026"
    assert rc_data["reward_type"] == "subscription_days"
    assert rc_data["reward_value"] == 7
    code_id = rc_data["id"]

    # 5.3 List redeem codes
    list_rc = await async_client.get(
        f"/api/v1/bots/{bot_id}/redeem-codes",
        headers=headers,
    )
    assert list_rc.status_code == 200
    assert any(c["code"] == "PROMO2026" for c in list_rc.json()["data"])

    # 5.4 Test Webhook execution for /redeem PROMO2026
    TelegramApiService.clear_sent_messages()
    resp_redeem = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10005,
            "message": {
                "from": {"id": 555222, "username": "promouser"},
                "chat": {"id": 555222},
                "text": "/redeem PROMO2026",
            },
        },
    )
    assert resp_redeem.status_code == 200
    sent_redeem = TelegramApiService.get_sent_messages()
    assert len(sent_redeem) >= 1
    assert "Redemption Successful" in sent_redeem[-1]["text"]

    # 5.5 Test 3-Way Trigger Toggle API
    # Turn OFF commands for redeem_codes
    trigger_patch = await async_client.patch(
        f"/api/v1/bots/{bot_id}/modules/redeem_codes/triggers",
        headers=headers,
        json={
            "enable_command": False,
            "enable_inline_button": True,
            "enable_menu_button": False,
        },
    )
    assert trigger_patch.status_code == 200
    trigger_data = trigger_patch.json()["data"]
    assert trigger_data["enable_command"] is False
    assert trigger_data["enable_inline_button"] is True
    assert trigger_data["enable_menu_button"] is False

    # 5.6 Now sending /redeem should be blocked because enable_command is False
    TelegramApiService.clear_sent_messages()
    resp_redeem_blocked = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json={
            "update_id": 10006,
            "message": {
                "from": {"id": 555333, "username": "blockeduser"},
                "chat": {"id": 555333},
                "text": "/redeem PROMO2026",
            },
        },
    )
    assert resp_redeem_blocked.status_code == 200
    sent_blocked = TelegramApiService.get_sent_messages()
    assert len(sent_blocked) >= 1
    assert "turned off by the bot administrator" in sent_blocked[-1]["text"]

