from typing import Dict, cast
import json
import re

from bs4 import BeautifulSoup as Soup

from .constants import WATCH_LATER_URL
from .typing.ytcfg import YtcfgDict


def find_ytcfg(soup: Soup) -> YtcfgDict:
    return cast(
        YtcfgDict,
        json.JSONDecoder().raw_decode(
            re.sub(
                r'.+ytcfg.set\(\{', '{',
                list(
                    filter(
                        lambda x: '"INNERTUBE_CONTEXT_CLIENT_VERSION":' in x.
                        text, soup.select('script')))[0].text.strip()))[0])


def ytcfg_headers(ytcfg: YtcfgDict) -> Dict[str, str]:
    return {
        'x-spf-previous': WATCH_LATER_URL,
        'x-spf-referer': WATCH_LATER_URL,
        'x-youtube-client-name': str(ytcfg['INNERTUBE_CONTEXT_CLIENT_NAME']),
        'x-youtube-client-version': ytcfg['INNERTUBE_CONTEXT_CLIENT_VERSION'],
        'x-youtube-identity-token': ytcfg['ID_TOKEN'],
        'x-youtube-page-cl': str(ytcfg['PAGE_CL']),
        'x-youtube-utc-offset': '-240',
        'x-youtube-variants-checksum': ytcfg['VARIANTS_CHECKSUM'],
    }

@@ -160,16 +160,40 @@
 cfgDict%0A
+from .util import first%0A
 %0A%0Adef fi
@@ -271,16 +271,22 @@
         
+first(
 json.JSO
@@ -389,43 +389,47 @@
     
-list(%0A                    filter(%0A 
+first(x for x in soup.select('script')%0A
     
@@ -450,18 +450,10 @@
     
- lambda x:
+if
  '%22I
@@ -493,11 +493,8 @@
 ' in
- x.
 %0A   
@@ -516,42 +516,15 @@
     
-  text, soup.select('script')))%5B0%5D
+x.text)
 .tex
@@ -538,11 +538,9 @@
 ()))
-%5B0%5D
+)
 )%0A%0A%0A

make use of first()