import re
import sys
import time
import random
import hashlib
import logging
from copy import deepcopy
from collections import OrderedDict

try:
    from HTMLParser import HTMLParser
except ImportError:
    if sys.version_info >= (3, 4):
        import html
    else:
        from html.parser import HTMLParser

try:
    from urlparse import urlparse, urljoin
except ImportError:
    from urllib.parse import urlparse, urljoin

from .exceptions import (
    CloudflareCode1020,
    CloudflareIUAMError,
    CloudflareSolveError,
    CloudflareChallengeError,
    CloudflareCaptchaError,
    CloudflareCaptchaProvider,
    TurnstileChallengeError,
    WAFDetectedError,
)
from .captcha import Captcha
from .interpreters import JavaScriptInterpreter

logger = logging.getLogger("nebulascrape.cloudflare")


class Cloudflare:
    def __init__(self, nebulascraper):
        self.nebulascraper = nebulascraper

    @staticmethod
    def unescape(html_text):
        if sys.version_info >= (3, 0):
            if sys.version_info >= (3, 4):
                return html.unescape(html_text)
            return HTMLParser().unescape(html_text)
        return HTMLParser().unescape(html_text)

    @staticmethod
    def is_IUAM_Challenge(resp):
        try:
            return (
                resp.headers.get('Server', '').startswith('cloudflare')
                and resp.status_code in [429, 503]
                and re.search(r'/cdn-cgi/images/trace/jsch/', resp.text, re.M | re.S)
                and re.search(
                    r'<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=',
                    resp.text, re.M | re.S
                )
            )
        except AttributeError:
            pass
        return False

    def is_New_IUAM_Challenge(self, resp):
        try:
            return (
                self.is_IUAM_Challenge(resp)
                and re.search(
                    r'''cpo\.src\s*=\s*['"]/cdn-cgi/challenge-platform/\S+orchestrate/jsch/v1''',
                    resp.text, re.M | re.S
                )
            )
        except AttributeError:
            pass
        return False

    def is_New_Captcha_Challenge(self, resp):
        try:
            return (
                self.is_Captcha_Challenge(resp)
                and re.search(
                    r'''cpo\.src\s*=\s*['"]/cdn-cgi/challenge-platform/\S+orchestrate/(captcha|managed)/v1''',
                    resp.text, re.M | re.S
                )
            )
        except AttributeError:
            pass
        return False

    @staticmethod
    def is_Captcha_Challenge(resp):
        try:
            return (
                resp.headers.get('Server', '').startswith('cloudflare')
                and resp.status_code == 403
                and re.search(r'/cdn-cgi/images/trace/(captcha|managed)/', resp.text, re.M | re.S)
                and re.search(
                    r'<form .*?="challenge-form" action="/\S+__cf_chl_f_tk=',
                    resp.text, re.M | re.S
                )
            )
        except AttributeError:
            pass
        return False

    @staticmethod
    def is_Firewall_Blocked(resp):
        try:
            return (
                resp.headers.get('Server', '').startswith('cloudflare')
                and resp.status_code == 403
                and re.search(
                    r'<span class="cf-error-code">1020</span>',
                    resp.text, re.M | re.DOTALL
                )
            )
        except AttributeError:
            pass
        return False

    @staticmethod
    def is_Turnstile_Challenge(resp):
        try:
            return (
                resp.headers.get('Server', '').startswith('cloudflare')
                and re.search(
                    r'cf-turnstile|challenges\.cloudflare\.com/turnstile',
                    resp.text, re.I | re.M
                )
            )
        except AttributeError:
            pass
        return False

    @staticmethod
    def is_Managed_Challenge(resp):
        try:
            return (
                resp.headers.get('Server', '').startswith('cloudflare')
                and resp.status_code in (403, 429, 503)
                and re.search(
                    r'orchestrate/(captcha|managed)/v1',
                    resp.text, re.M | re.S
                )
            )
        except AttributeError:
            pass
        return False

    def is_Challenge_Request(self, resp):
        if self.is_Firewall_Blocked(resp):
            self.nebulascraper.simpleException(
                CloudflareCode1020,
                'Cloudflare has blocked this request (Code 1020 Detected).'
            )

        if self.is_Turnstile_Challenge(resp):
            self.nebulascraper.simpleException(
                TurnstileChallengeError,
                'Cloudflare Turnstile challenge detected — use TransportHeadless with curl_cffi for bypass.'
            )

        if self.is_New_Captcha_Challenge(resp):
            self.nebulascraper.simpleException(
                CloudflareChallengeError,
                'Cloudflare v2 Captcha/Managed challenge detected.'
            )

        if self.is_New_IUAM_Challenge(resp):
            self.nebulascraper.simpleException(
                CloudflareChallengeError,
                'Cloudflare v2 IUAM challenge detected.'
            )

        if self.is_Captcha_Challenge(resp) or self.is_IUAM_Challenge(resp):
            logger.debug('[Cloudflare] Detected v1 challenge.')
            return True

        return False

    def _browser_delay(self, body: str):
        delay = None
        if not self.nebulascraper.delay:
            try:
                delay = float(
                    re.search(r'submit\(\);\r?\n\s*},\s*([0-9]+)', body).group(1)
                ) / 1000.0
            except (AttributeError, ValueError):
                delay = 4.0
            self.nebulascraper.delay = delay

        jitter = random.uniform(-0.2, 0.4)
        sleep_time = max(0, self.nebulascraper.delay + jitter)
        logger.debug(f"[Cloudflare] Browser-realistic delay: {sleep_time:.2f}s")
        time.sleep(sleep_time)

    def IUAM_Challenge_Response(self, body, url, interpreter):
        try:
            formPayload = re.search(
                r'<form (?P<form>.*?="challenge-form" '
                r'action="(?P<challengeUUID>.*?'
                r'__cf_chl_f_tk=\S+)"(.*?)</form>)',
                body, re.M | re.DOTALL
            ).groupdict()

            if not all(key in formPayload for key in ['form', 'challengeUUID']):
                self.nebulascraper.simpleException(
                    CloudflareIUAMError,
                    "Cloudflare IUAM — could not extract form parameters."
                )

            payload = OrderedDict()
            for challengeParam in re.findall(r'^\s*<input\s(.*?)/>', formPayload['form'], re.M | re.S):
                inputPayload = dict(re.findall(r'(\S+)="(\S+)"', challengeParam))
                if inputPayload.get('name') in ['r', 'jschl_vc', 'pass']:
                    payload.update({inputPayload['name']: inputPayload['value']})

        except AttributeError:
            self.nebulascraper.simpleException(
                CloudflareIUAMError,
                "Cloudflare IUAM — could not extract form parameters."
            )

        hostParsed = urlparse(url)
        try:
            payload['jschl_answer'] = JavaScriptInterpreter.dynamicImport(
                interpreter
            ).solveChallenge(body, hostParsed.netloc)
        except Exception as e:
            self.nebulascraper.simpleException(
                CloudflareIUAMError,
                f"Unable to solve Cloudflare challenge: {getattr(e, 'message', e)}"
            )

        return {
            'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}",
            'data': payload
        }

    def captcha_Challenge_Response(self, provider, provider_params, body, url):
        try:
            formPayload = re.search(
                r'<form (?P<form>.*?="challenge-form" '
                r'action="(?P<challengeUUID>.*?__cf_chl_captcha_tk__=\S+)"(.*?)</form>)',
                body, re.M | re.DOTALL
            ).groupdict()

            if not all(key in formPayload for key in ['form', 'challengeUUID']):
                self.nebulascraper.simpleException(
                    CloudflareCaptchaError,
                    "Cloudflare Captcha — could not extract parameters."
                )

            payload = OrderedDict(
                re.findall(
                    r'(name="r"\svalue|data-ray|data-sitekey|name="cf_captcha_kind"\svalue)="(.*?)"',
                    formPayload['form']
                )
            )
            captchaType = 'reCaptcha' if payload.get('name="cf_captcha_kind" value') == 're' else 'hCaptcha'

        except (AttributeError, KeyError):
            self.nebulascraper.simpleException(
                CloudflareCaptchaError,
                "Cloudflare Captcha — could not extract parameters."
            )

        if self.nebulascraper.proxies and self.nebulascraper.proxies != self.nebulascraper.captcha.get('proxy'):
            self.nebulascraper.captcha['proxy'] = self.nebulascraper.proxies

        self.nebulascraper.captcha['User-Agent'] = self.nebulascraper.headers['User-Agent']

        captchaResponse = Captcha.dynamicImport(provider.lower()).solveCaptcha(
            captchaType, url, payload.get('data-sitekey'), provider_params
        )

        dataPayload = OrderedDict([
            ('r', payload.get('name="r" value', '')),
            ('cf_captcha_kind', payload.get('name="cf_captcha_kind" value', '')),
            ('id', payload.get('data-ray')),
            ('g-recaptcha-response', captchaResponse)
        ])

        if captchaType == 'hCaptcha':
            dataPayload.update({'h-captcha-response': captchaResponse})

        hostParsed = urlparse(url)
        return {
            'url': f"{hostParsed.scheme}://{hostParsed.netloc}{self.unescape(formPayload['challengeUUID'])}",
            'data': dataPayload
        }

    def Challenge_Response(self, resp, **kwargs):
        if self.is_Captcha_Challenge(resp):
            if self.nebulascraper.doubleDown:
                resp = self.nebulascraper.decodeBrotli(
                    self.nebulascraper.perform_request(resp.request.method, resp.url, **kwargs)
                )

            if not self.is_Captcha_Challenge(resp):
                return resp

            if (
                not self.nebulascraper.captcha
                or not isinstance(self.nebulascraper.captcha, dict)
                or not self.nebulascraper.captcha.get('provider')
            ):
                self.nebulascraper.simpleException(
                    CloudflareCaptchaProvider,
                    "Cloudflare Captcha detected — no captcha provider configured."
                )

            if self.nebulascraper.captcha.get('provider') == 'return_response':
                return resp

            submit_url = self.captcha_Challenge_Response(
                self.nebulascraper.captcha.get('provider'),
                self.nebulascraper.captcha,
                resp.text,
                resp.url
            )
        else:
            self._browser_delay(resp.text)

            submit_url = self.IUAM_Challenge_Response(
                resp.text, resp.url, self.nebulascraper.interpreter
            )

        if submit_url:
            def updateAttr(obj, name, newValue):
                try:
                    obj[name].update(newValue)
                    return obj[name]
                except (AttributeError, KeyError):
                    obj[name] = {}
                    obj[name].update(newValue)
                    return obj[name]

            cf_kwargs = deepcopy(kwargs)
            cf_kwargs['allow_redirects'] = False
            cf_kwargs['data'] = updateAttr(cf_kwargs, 'data', submit_url['data'])

            urlParsed = urlparse(resp.url)
            cf_kwargs['headers'] = updateAttr(cf_kwargs, 'headers', {
                'Origin': f'{urlParsed.scheme}://{urlParsed.netloc}',
                'Referer': resp.url
            })

            challengeSubmitResponse = self.nebulascraper.request(
                'POST', submit_url['url'], **cf_kwargs
            )

            if challengeSubmitResponse.status_code == 400:
                self.nebulascraper.simpleException(
                    CloudflareSolveError,
                    'Invalid challenge answer — Cloudflare rejected the response.'
                )

            if not challengeSubmitResponse.is_redirect:
                return challengeSubmitResponse

            cf_kwargs = deepcopy(kwargs)
            cf_kwargs['headers'] = updateAttr(
                cf_kwargs, 'headers', {'Referer': challengeSubmitResponse.url}
            )

            if not urlparse(challengeSubmitResponse.headers['Location']).netloc:
                redirect_location = urljoin(
                    challengeSubmitResponse.url,
                    challengeSubmitResponse.headers['Location']
                )
            else:
                redirect_location = challengeSubmitResponse.headers['Location']

            return self.nebulascraper.request(
                resp.request.method, redirect_location, **cf_kwargs
            )

        return self.nebulascraper.request(resp.request.method, resp.url, **kwargs)
