from utils.logger import logger

import asyncio
import aiohttp

CAPSOLVER_TOKEN = 'CAP-CF968C755F8DBD247DE977D07332B98F'
TURNSTILE_SECRET = '0x4AAAAAABeYcUT3Qbli4gsp'

async def capslover_create_task(website_url: str) -> dict:
    url = 'https://api.capsolver.com/createTask'
    payload = {
        'clientKey': CAPSOLVER_TOKEN,
        'task': {
            'type': 'AntiTurnstileTaskProxyLess',
            'websiteURL': website_url,
            'websiteKey': TURNSTILE_SECRET
        }
    }
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers={'Content-Type': 'application/json'}, timeout=60) as resp:
                if resp.status == 200:
                    return await resp.json()
                else:
                    logger.error(f'<red>[-]</red> Capsolver createTask status: {resp.status}')
                    return None
    except Exception as error:
        logger.error(f'<red>[-]</red> Capsolver createTask exception: {error}')
        return None


async def capslover_getTaskResult(task_id: str) -> dict:
    url = 'https://api.capsolver.com/getTaskResult'
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json={'clientKey': CAPSOLVER_TOKEN, 'taskId': task_id}, headers={'Content-Type': 'application/json'}, timeout=60) as resp:
                if resp.status == 200:
                    return await resp.json()
                else:
                    logger.error(f'<red>[-]</red> Capsolver getTaskResult status: {resp.status}')
                    return None
    except Exception as error:
        logger.error(f'<red>[-]</red> Capsolver getTaskResult exception: {error}')
        return None


async def wait_for_captcha(task_id: str, timeout: int = 120) -> dict:
    start = asyncio.get_event_loop().time()
    
    while True:
        res = await capslover_getTaskResult(task_id)
        if res is None:
            return None
        
        if res.get('status') == 'ready':
            return res.get('solution', {}).get('token')
        
        if asyncio.get_event_loop().time() - start > timeout:
            logger.error('<red>[-]</red> Captcha wait timed out.')
            return None
        
        await asyncio.sleep(3)


async def telegram_check_captcha(token: str, actor: str, scope: str = 'sbot_spam') -> dict:
    url = 'https://telegram.org/captcha/checkcaptcha'
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, data={'token': token, 'actor': actor, 'scope': scope}, timeout=30) as resp:
                if resp.status == 200:
                    return await resp.json()
                else:
                    logger.error(f'<red>[-]</red> Telegram checkcaptcha status: {resp.status}')
                    return None
    except Exception as error:
        logger.error(f'<red>[-]</red> Telegram_check_captcha exception: {error}')
        return None
