import uuid
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from modules.tenants.models import Tenant
from modules.bots.models import Bot
from modules.bots.modular_engine import BotModuleService, CORE_MODULE_DEFINITIONS
from infrastructure.telegram.service import TelegramApiService


async def create_dummy_bot(db_session: AsyncSession, name: str = "Test Bot") -> Bot:
    tenant_id = uuid.uuid4()
    tenant = Tenant(
        id=tenant_id,
        name=f"Tenant {uuid.uuid4().hex[:6]}",
        slug=f"slug-{uuid.uuid4().hex[:8]}",
        status="active",
        default_locale="en",
    )
    db_session.add(tenant)
    await db_session.flush()

    bot = Bot(
        id=uuid.uuid4(),
        tenant_id=tenant_id,
        name=name,
        username=f"bot_{uuid.uuid4().hex[:8]}",
        status="active",
        default_locale="en",
    )
    db_session.add(bot)
    await db_session.commit()
    return bot


@pytest.mark.asyncio
async def test_module_catalog_definitions():
    """Verifies all 9 core modules are fully defined with schema and defaults."""
    expected_modules = {
        "welcome_message",
        "force_join",
        "referrals",
        "redeem_codes",
        "broadcasts",
        "user_management",
        "auto_filter",
        "payments",
        "subscriptions",
        "ai_assistant",
        "logs_tracker",
        "captcha_gate",
        "file_store",
        "support_tickets",
        "crypto_payments",
        "auto_kick",
        "daily_rewards",
        "content_protection",
    }
    assert set(CORE_MODULE_DEFINITIONS.keys()) == expected_modules

    for mod_id, meta in CORE_MODULE_DEFINITIONS.items():
        assert "name" in meta
        assert "category" in meta
        assert "default_config" in meta
        assert "permissions" in meta
        assert len(meta["permissions"]) > 0


@pytest.mark.asyncio
async def test_bot_module_lifecycle(db_session: AsyncSession):
    """Tests install, list, toggle on/off, update config, and uninstall of bot modules."""
    bot = await create_dummy_bot(db_session, "Modular Test Bot")
    bot_id = bot.id

    service = BotModuleService(db_session)

    # 1. List modules initially - none installed
    modules = await service.list_bot_modules(bot_id)
    assert len(modules) == 18
    assert all(not m["is_installed"] for m in modules)

    # 2. Install 'force_join'
    mod = await service.install_module(
        bot_id,
        "force_join",
        config={"channel_username": "@my_vip_channel", "button_text": "Join Now"},
    )
    assert mod.module_id == "force_join"
    assert mod.is_enabled is True
    assert mod.config["channel_username"] == "@my_vip_channel"

    # 3. Verify is_module_active
    assert await service.is_module_active(bot_id, "force_join") is True
    assert await service.is_module_active(bot_id, "referrals") is False

    # 4. Toggle OFF
    toggled = await service.toggle_module(bot_id, "force_join", is_enabled=False)
    assert toggled.is_enabled is False
    assert await service.is_module_active(bot_id, "force_join") is False

    # 5. Toggle ON
    toggled_on = await service.toggle_module(bot_id, "force_join", is_enabled=True)
    assert toggled_on.is_enabled is True
    assert await service.is_module_active(bot_id, "force_join") is True

    # 6. Update config
    updated = await service.update_module_config(
        bot_id,
        "force_join",
        config={"channel_username": "@new_channel", "button_text": "Enter"},
    )
    assert updated.config["channel_username"] == "@new_channel"

    # 7. Uninstall module
    await service.uninstall_module(bot_id, "force_join")
    assert await service.is_module_active(bot_id, "force_join") is False


@pytest.mark.asyncio
async def test_force_join_gating_behavior(db_session: AsyncSession):
    """Verifies that force_join gates non-members and passes active members."""
    bot = await create_dummy_bot(db_session, "Gate Bot")
    bot_id = bot.id

    service = BotModuleService(db_session)
    await service.install_module(
        bot_id,
        "force_join",
        config={"channel_username": "@exclusive_gate", "button_text": "Join Here"},
    )

    # Simulated member (default in mock) -> passes
    is_allowed, prompt = await service.check_force_join(
        bot_id=bot_id,
        raw_token="mock_token_gate",
        user_id=123456,
    )
    assert is_allowed is True
    assert prompt is None

    # Simulated non-member (user 999000 returns 'left' status in mock)
    is_blocked, block_prompt = await service.check_force_join(
        bot_id=bot_id,
        raw_token="mock_token_gate",
        user_id=999000,
    )
    assert is_blocked is False
    assert block_prompt is not None
    assert "Channel Membership Required" in block_prompt["text"]

    # When deactivated -> non-members are NOT blocked!
    await service.toggle_module(bot_id, "force_join", is_enabled=False)
    is_allowed_deactivated, prompt_deactivated = await service.check_force_join(
        bot_id=bot_id,
        raw_token="mock_token_gate",
        user_id=999000,
    )
    assert is_allowed_deactivated is True
    assert prompt_deactivated is None


@pytest.mark.asyncio
async def test_referrals_and_growth_attribution(db_session: AsyncSession):
    """Verifies deep-link referral tracking, points calculation, and toggle enforcement."""
    bot = await create_dummy_bot(db_session, "Referral Bot")
    bot_id = bot.id

    service = BotModuleService(db_session)

    # 1. When deactivated, referral attribution fails
    res_inactive = await service.record_referral(
        bot_id=bot_id,
        new_user_id=888001,
        referrer_user_id=777001,
    )
    assert res_inactive["ok"] is False

    # 2. Activate referrals
    await service.install_module(
        bot_id,
        "referrals",
        config={"points_per_referral": 15, "min_payout_points": 50},
    )

    # 3. Refer subscriber
    res_active = await service.record_referral(
        bot_id=bot_id,
        new_user_id=888001,
        referrer_user_id=777001,
    )
    assert res_active["ok"] is True
    assert res_active["points"] == 15

    # 4. Duplicate referral dropped
    res_dup = await service.record_referral(
        bot_id=bot_id,
        new_user_id=888001,
        referrer_user_id=777001,
    )
    assert res_dup["ok"] is False
    assert res_dup["reason"] == "Already referred"

    # 5. Self-referral prevented
    res_self = await service.record_referral(
        bot_id=bot_id,
        new_user_id=777001,
        referrer_user_id=777001,
    )
    assert res_self["ok"] is False

    # 6. Second invite for same referrer
    await service.record_referral(
        bot_id=bot_id,
        new_user_id=888002,
        referrer_user_id=777001,
    )

    # 7. Summary calculation
    summary = await service.get_referral_summary(
        bot_id=bot_id,
        user_id=777001,
        bot_username=bot.username,
    )
    assert summary["referral_count"] == 2
    assert summary["referral_points"] == 30  # 2 * 15
    assert "start=ref_777001" in summary["invite_link"]


@pytest.mark.asyncio
async def test_auto_filter_keyword_and_blocked_words(db_session: AsyncSession):
    """Verifies that auto-filter detects blocked words and matches keywords when active."""
    bot = await create_dummy_bot(db_session, "Filter Bot")
    bot_id = bot.id

    service = BotModuleService(db_session)
    await service.install_module(
        bot_id,
        "auto_filter",
        config={
            "rules": [
                {"trigger": "pricing", "match_type": "contains", "response": "Plans start at ₹999/mo."},
                {"trigger": "support", "match_type": "exact", "response": "Contact human help at @desk."},
            ],
            "blocked_words": ["scam", "phishing"],
            "action_on_blocked": "warn",
        },
    )

    # Blocked word match
    action, resp = await service.evaluate_auto_filter(bot_id, "This looks like a scam link")
    assert action == "warn"
    assert "prohibited term 'scam'" in resp

    # Keyword contains match
    action_kw, resp_kw = await service.evaluate_auto_filter(bot_id, "What is the pricing?")
    assert action_kw is None
    assert resp_kw == "Plans start at ₹999/mo."

    # Deactivated -> bypasses all checks
    await service.toggle_module(bot_id, "auto_filter", is_enabled=False)
    act_off, resp_off = await service.evaluate_auto_filter(bot_id, "This is a scam")
    assert act_off is None
    assert resp_off is None


@pytest.mark.asyncio
async def test_redeem_code_lifecycle_and_redemption(db_session: AsyncSession):
    """Verifies Redeem Code creation, anti-abuse checks, point/VIP rewards, and expiry."""
    from datetime import datetime, timezone, timedelta

    bot = await create_dummy_bot(db_session, "Redeem Bot")
    bot_id = bot.id
    service = BotModuleService(db_session)

    # 1. Install redeem_codes module
    await service.install_module(bot_id, "redeem_codes")

    # 2. Create VIP code with max_uses=1
    vip_code = await service.create_redeem_code(
        bot_id=bot_id,
        code="VIP-SUPER-30",
        reward_type="subscription_days",
        reward_value=30,
        max_uses=1,
    )
    assert vip_code.code == "VIP-SUPER-30"
    assert vip_code.times_used == 0

    # 3. Create Points code
    pts_code = await service.create_redeem_code(
        bot_id=bot_id,
        code="POINTS-100",
        reward_type="points",
        reward_value=100,
        max_uses=10,
    )
    assert pts_code.code == "POINTS-100"

    # 4. User A redeems VIP code
    ok1, msg1, data1 = await service.redeem_code_for_user(
        bot_id=bot_id,
        telegram_user_id=1001,
        raw_code="VIP-SUPER-30",
    )
    assert ok1 is True
    assert data1["reward_type"] == "subscription_days"
    assert data1["reward_value"] == 30

    # 5. User A tries to redeem same VIP code again -> duplicate rejected
    ok_dup, msg_dup, _ = await service.redeem_code_for_user(
        bot_id=bot_id,
        telegram_user_id=1001,
        raw_code="VIP-SUPER-30",
    )
    assert ok_dup is False
    assert "already redeemed" in msg_dup.lower()

    # 6. User B tries to redeem VIP code -> max_uses reached rejected
    ok_limit, msg_limit, _ = await service.redeem_code_for_user(
        bot_id=bot_id,
        telegram_user_id=1002,
        raw_code="VIP-SUPER-30",
    )
    assert ok_limit is False
    assert "limit" in msg_limit.lower()

    # 7. User A redeems points code -> success
    ok_pts, msg_pts, data_pts = await service.redeem_code_for_user(
        bot_id=bot_id,
        telegram_user_id=1001,
        raw_code="points-100",  # Case insensitive check
    )
    assert ok_pts is True
    assert data_pts["reward_type"] == "points"
    assert data_pts["reward_value"] == 100

    # 8. Expired code test
    expired_code = await service.create_redeem_code(
        bot_id=bot_id,
        code="EXPIRED-99",
        reward_type="points",
        reward_value=50,
        expires_at=datetime.now(timezone.utc) - timedelta(days=1),
    )
    ok_exp, msg_exp, _ = await service.redeem_code_for_user(
        bot_id=bot_id,
        telegram_user_id=1003,
        raw_code="EXPIRED-99",
    )
    assert ok_exp is False
    assert "expired" in msg_exp.lower()

    # 9. Inactive module test -> redemption fails if module is disabled
    await service.toggle_module(bot_id, "redeem_codes", is_enabled=False)
    assert await service.is_module_active(bot_id, "redeem_codes") is False


@pytest.mark.asyncio
async def test_three_way_triggers_and_menu_generation(db_session: AsyncSession):
    """Verifies 3-way toggle controls (command, inline_button, menu_button) and dynamic keyboard building."""
    bot = await create_dummy_bot(db_session, "Trigger Bot")
    bot_id = bot.id
    service = BotModuleService(db_session)

    # Install redeem_codes and referrals
    mod_redeem = await service.install_module(bot_id, "redeem_codes")
    mod_ref = await service.install_module(bot_id, "referrals")

    # Initial state: all 3 triggers enabled by default
    assert mod_redeem.enable_command is True
    assert mod_redeem.enable_inline_button is True
    assert mod_redeem.enable_menu_button is True

    # Check is_trigger_allowed
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "command") is True
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "inline_button") is True
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "menu_button") is True

    # Generate menus - both modules should be in menus
    reply_markup = await service.build_dynamic_reply_menu(bot_id)
    assert reply_markup is not None
    # Flatten keyboard buttons to check texts
    menu_buttons = [btn["text"] for row in reply_markup["keyboard"] for btn in row]
    assert "🎁 Redeem Code" in menu_buttons
    assert "👥 Invite Friends" in menu_buttons

    inline_markup = await service.build_dynamic_inline_menu(bot_id)
    assert inline_markup is not None
    inline_callbacks = [btn["callback_data"] for row in inline_markup["inline_keyboard"] for btn in row]
    assert "mod_redeem_codes" in inline_callbacks
    assert "mod_referrals" in inline_callbacks

    # Now toggle redeem_codes: turn OFF menu_button and inline_button, leave command ON
    await service.toggle_module_triggers(
        bot_id=bot_id,
        module_id="redeem_codes",
        enable_command=True,
        enable_inline_button=False,
        enable_menu_button=False,
    )

    # Check permissions
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "command") is True
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "inline_button") is False
    assert await service.is_trigger_allowed(bot_id, "redeem_codes", "menu_button") is False

    # Dynamic menus should now omit redeem_codes
    updated_reply = await service.build_dynamic_reply_menu(bot_id)
    updated_menu_buttons = [btn["text"] for row in updated_reply["keyboard"] for btn in row]
    assert "🎁 Redeem Code" not in updated_menu_buttons
    assert "👥 Invite Friends" in updated_menu_buttons

    updated_inline = await service.build_dynamic_inline_menu(bot_id)
    updated_inline_callbacks = [btn["callback_data"] for row in updated_inline["inline_keyboard"] for btn in row]
    assert "mod_redeem_codes" not in updated_inline_callbacks
    assert "mod_referrals" in updated_inline_callbacks


@pytest.mark.asyncio
async def test_captcha_and_daily_rewards_lifecycle(db_session: AsyncSession):
    """Verifies Captcha verification gating and Daily Rewards streak gamification."""
    bot = await create_dummy_bot(db_session, "Gamified Gate Bot")
    bot_id = bot.id
    service = BotModuleService(db_session)

    # 1. Install captcha_gate & daily_rewards
    await service.install_module(bot_id, "captcha_gate")
    await service.install_module(bot_id, "daily_rewards", config={"base_points": 10, "streak_multiplier": 1.5})

    # User 5001 unverified initially
    is_ok, prompt = await service.check_captcha_status(bot_id, 5001)
    assert is_ok is False
    assert prompt is not None
    assert "Anti-Bot Verification Required" in prompt["text"]

    # Verify user 5001
    res_verify = await service.verify_captcha_for_user(bot_id, 5001)
    assert res_verify["ok"] is True

    # Now passes check
    is_ok_verified, prompt_v = await service.check_captcha_status(bot_id, 5001)
    assert is_ok_verified is True
    assert prompt_v is None

    # Claim Day 1 Daily Reward
    res_d1 = await service.claim_daily_reward(bot_id, 5001)
    assert res_d1["ok"] is True
    assert res_d1["points_awarded"] == 10
    assert res_d1["streak_count"] == 1
    assert res_d1["total_points"] == 10

    # Claim second time immediately -> fails with cooldown
    res_d_dup = await service.claim_daily_reward(bot_id, 5001)
    assert res_d_dup["ok"] is False
    assert "Already Claimed Today" in res_d_dup["message"]


@pytest.mark.asyncio
async def test_file_store_and_support_tickets_lifecycle(db_session: AsyncSession):
    """Verifies Digital File Store downloads and 2-way Support Tickets."""
    bot = await create_dummy_bot(db_session, "Store Support Bot")
    bot_id = bot.id
    service = BotModuleService(db_session)

    # Install file_store and support_tickets
    await service.install_module(bot_id, "file_store")
    await service.install_module(bot_id, "support_tickets")

    # 1. Create file in store
    file_record = await service.create_bot_file(
        bot_id=bot_id,
        file_id="tg_file_id_xyz999",
        file_name="Python Mastery Guide.pdf",
        access_type="points",
        cost=15,
        unlock_code="PYTHON101",
    )
    assert file_record.unlock_code == "PYTHON101"
    assert file_record.downloads_count == 0

    # User 6001 tries to unlock without enough points -> rejected
    ok_unlock, msg_u, f_obj = await service.unlock_file_for_user(bot_id, 6001, "PYTHON101")
    assert ok_unlock is False
    assert "Insufficient points" in msg_u

    # User 6002 unlocks free file
    free_file = await service.create_bot_file(
        bot_id=bot_id,
        file_id="tg_file_id_free123",
        file_name="Free Starter CheatSheet.pdf",
        access_type="free",
        cost=0,
        unlock_code="FREE101",
    )
    ok_free, msg_free, f_free = await service.unlock_file_for_user(bot_id, 6002, "FREE101")
    assert ok_free is True
    assert f_free.downloads_count == 1

    # 2. Support Ticket
    ticket = await service.create_support_ticket(
        bot_id=bot_id,
        telegram_user_id=6001,
        subject="Payment didn't reflect",
        username="john_doe",
    )
    assert ticket.subject == "Payment didn't reflect"
    assert ticket.status == "open"

    # List tickets
    tickets = await service.list_support_tickets(bot_id)
    assert len(tickets) >= 1
    assert any(t.id == ticket.id for t in tickets)



