import requests
import time
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

from config.load_env import load_environment_variables
from services.my_slack import send_slack_message
import os

#環境変数の読み込み
load_environment_variables()

# 2CaptchaのAPIキーを設定
TWO_CAPTCHA_API_KEY = os.getenv("TWO_CAPTCHA_API_KEY")
# サイトキーとページURLを設定
TWO_CAPTCHA_SITE_KEY = os.getenv("TWO_CAPTCHA_SITE_KEY")
TWO_CAPTCHA_PAGE_URL = os.getenv("TWO_CAPTCHA_PAGE_URL")

def get_captcha_solution():
    try:
        # 2CaptchaにreCAPTCHA V2の解決を依頼
        response = requests.post('http://2captcha.com/in.php', data={
            'key': TWO_CAPTCHA_API_KEY,
            'method': 'userrecaptcha',
            'googlekey': TWO_CAPTCHA_SITE_KEY,
            'pageurl': TWO_CAPTCHA_PAGE_URL,
            'json': 1
        })
        request_id = response.json().get('request')
        
        if not request_id:
            raise Exception('Failed to get request ID from 2Captcha.')

        # 2Captchaの解決結果を取得
        solution = None
        for _ in range(6):
            response = requests.get('http://2captcha.com/res.php', params={
                'key': TWO_CAPTCHA_API_KEY,
                'action': 'get',
                'id': request_id,
                'json': 1
            })
            print(response.json())
            result = response.json()
            if result.get('status') == 1:
                solution = result.get('request')
                break
            else:
                time.sleep(20)  # 待機時間を設定

        if not solution:
            error_message = "<!subteam^S08AB4JUL92>TwoCaptchaで、レスポンスがありませんでした。再度実行をお願いします。"
            send_slack_message(error_message, "WEBHOOK_URL_CS_NOTICE")
            raise Exception('Failed to get captcha solution from 2Captcha.')

        return solution
    except Exception as e:
        return e
