import asyncio
import httpx
import sys

BASE_URL = "http://localhost:8080"
EMAIL = "admin@telebotcloud.com"
PASSWORD = "TeleBotAdmin2026!"

async def run_tests():
    async with httpx.AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
        print("=== 1. Logging in as Admin ===")
        login_res = await client.post("/api/v1/auth/login", json={"email": EMAIL, "password": PASSWORD})
        print(f"Login status: {login_res.status_code}")
        if login_res.status_code != 200:
            print("Login error:", login_res.text)
            sys.exit(1)
            
        token_data = login_res.json()
        token = token_data.get("access_token") or token_data.get("token") or token_data.get("data", {}).get("access_token")
        headers = {"Authorization": f"Bearer {token}"}
        print(f"Token obtained: {token[:15]}...")

        print("\n=== 2. Fetching User Bots ===")
        bots_res = await client.get("/api/v1/bots", headers=headers)
        print(f"Bots status: {bots_res.status_code}")
        bots = bots_res.json()
        bot_list = bots if isinstance(bots, list) else bots.get("data", [])
        
        bot_id = None
        if bot_list:
            bot_id = bot_list[0]["id"]
            print(f"Using existing bot: {bot_list[0].get('username')} ({bot_id})")
        else:
            print("Creating test bot...")
            create_res = await client.post("/api/v1/bots", headers=headers, json={
                "name": "AuditBot",
                "token": "123456789:ABCdefGHIjklMNOpqrSTUvwxYZ123456789",
                "default_locale": "en"
            })
            print(f"Create bot status: {create_res.status_code}, body: {create_res.text}")
            if create_res.status_code in [200, 201]:
                b_data = create_res.json().get("data", create_res.json())
                bot_id = b_data["id"]

        if not bot_id:
            print("ERROR: No bot available to test")
            sys.exit(1)

        print(f"\n=== 3. Testing Logs Tracker Verification on Bot {bot_id} ===")
        # Test 3a: Empty chat ID
        empty_res = await client.post(f"/api/v1/bots/{bot_id}/modules/logs_tracker/verify", headers=headers, json={
            "config": {"log_channel_id": ""},
            "chat_id": ""
        })
        print(f"Empty channel verify: {empty_res.status_code}, response: {empty_res.json()}")
        assert empty_res.status_code == 200
        assert empty_res.json()["data"]["ok"] is False

        # Test 3b: Test invalid chat (real Telegram API check)
        check_res = await client.post(f"/api/v1/bots/{bot_id}/modules/logs_tracker/verify", headers=headers, json={
            "config": {
                "log_channel_id": "@nonexistent_telebot_test_chat_9999",
                "log_channel_type": "supergroup_forum",
                "enable_topics": True
            },
            "chat_id": "@nonexistent_telebot_test_chat_9999",
            "test_topic": True
        })
        print(f"Real Telegram API check status: {check_res.status_code}")
        check_data = check_res.json()["data"]
        print(f"  OK: {check_data.get('ok')}")
        print(f"  Is Admin: {check_data.get('is_admin')}")
        print(f"  Is Forum: {check_data.get('is_forum')}")
        print(f"  Can Topics: {check_data.get('can_manage_topics')}")
        print(f"  Topic Supported: {check_data.get('topics_supported')}")
        print(f"  Message: {check_data.get('message')}")
        print(f"  Checks: {check_data.get('checks')}")
        assert check_data.get("is_admin") is False  # Bot is definitely not admin in nonexistent chat

        print("\n=== 4. Testing Force Join Verification ===")
        fj_res = await client.post(f"/api/v1/bots/{bot_id}/modules/force_join/verify", headers=headers, json={
            "config": {"channel_username": "@test_channel_missing"},
            "chat_id": "@test_channel_missing"
        })
        print(f"Force Join verify status: {fj_res.status_code}")
        fj_data = fj_res.json()["data"]
        print(f"  OK: {fj_data.get('ok')}, Is Admin: {fj_data.get('is_admin')}")
        assert fj_data.get("is_admin") is False

        print("\n=== 5. Testing Self-Contained Modules Verification ===")
        modules_to_test = [
            ("welcome_message", {"welcome_text": "Hello {first_name}! Welcome to {bot_name}!", "buttons_count": 2}),
            ("ai_assistant", {"model": "gpt-4o-mini", "system_prompt": "You are a friendly customer service assistant."}),
            ("broadcasts", {"rate_limit_per_second": 25, "allow_opt_out": True}),
            ("payments", {"gateway": "razorpay", "currency": "INR"}),
            ("subscriptions", {"tiers": [{"name": "VIP Monthly", "price": 499}], "grace_period_days": 3}),
            ("auto_filter", {"rules": [{"keyword": "help", "response": "Here is help"}], "blocked_words": ["spam"]}),
            ("referrals", {"points_per_referral": 10}),
            ("user_management", {"auto_detect_locale": True})
        ]

        for mod_id, cfg in modules_to_test:
            mod_res = await client.post(f"/api/v1/bots/{bot_id}/modules/{mod_id}/verify", headers=headers, json={
                "config": cfg
            })
            print(f"Module '{mod_id}' verify status: {mod_res.status_code}")
            mod_data = mod_res.json().get("data", {})
            print(f"  -> ok: {mod_data.get('ok')}, checks: {len(mod_data.get('checks', []))}")
            assert mod_res.status_code == 200
            assert mod_data.get("ok") is True

        print("\n=== 6. Testing Toggle Module Endpoint with Auto-Verification ===")
        # Toggle ON welcome_message
        toggle_res = await client.post(f"/api/v1/bots/{bot_id}/modules/welcome_message/toggle", headers=headers, json={
            "is_enabled": True
        })
        print(f"Toggle welcome_message status: {toggle_res.status_code}")
        toggle_data = toggle_res.json()["data"]
        print(f"  is_enabled: {toggle_data.get('is_enabled')}")
        print(f"  verification: {toggle_data.get('verification', {}).get('ok')}")
        assert toggle_data.get("is_enabled") is True
        assert toggle_data.get("verification", {}).get("ok") is True

        # Toggle OFF welcome_message
        toggle_off_res = await client.post(f"/api/v1/bots/{bot_id}/modules/welcome_message/toggle", headers=headers, json={
            "is_enabled": False
        })
        assert toggle_off_res.json()["data"]["is_enabled"] is False
        print("  Toggle off successful.")

        print("\n=== 7. Testing Patch Config Endpoint with Verification Status ===")
        patch_res = await client.patch(f"/api/v1/bots/{bot_id}/modules/ai_assistant/config", headers=headers, json={
            "config": {
                "model": "gpt-4o-mini",
                "system_prompt": "Updated system persona prompt for TeleBot AI."
            }
        })
        print(f"Patch config status: {patch_res.status_code}")
        patch_data = patch_res.json()["data"]
        print(f"  verification ok: {patch_data.get('verification', {}).get('ok')}")
        assert patch_res.status_code == 200
        assert patch_data.get("verification", {}).get("ok") is True

        print("\n🎉 ALL BACKEND VERIFICATION ENDPOINTS PASSED SUCCESSFULLY! 🎉")

if __name__ == "__main__":
    asyncio.run(run_tests())
