# coding: utf-8
from __future__ import unicode_literals

import re

from .common import InfoExtractor
from ..utils import (
    compat_str,
    float_or_none,
    int_or_none,
)


class STVPlayerIE(InfoExtractor):
    IE_NAME = 'stv:player'
    _VALID_URL = r'https?://player\.stv\.tv/(?P<type>episode|video)/(?P<id>[a-z0-9]{4})'
    _TEST = {
        'url': 'https://player.stv.tv/video/4gwd/emmerdale/60-seconds-on-set-with-laura-norton/',
        'md5': '5adf9439c31d554f8be0707c7abe7e0a',
        'info_dict': {
            'id': '5333973339001',
            'ext': 'mp4',
            'upload_date': '20170301',
            'title': '60 seconds on set with Laura Norton',
            'description': "How many questions can Laura - a.k.a Kerry Wyatt - answer in 60 seconds? Let\'s find out!",
            'timestamp': 1488388054,
            'uploader_id': '1486976045',
        },
        'skip': 'this resource is unavailable outside of the UK',
    }
    BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/1486976045/default_default/index.html?videoId=%s'
    _PTYPE_MAP = {
        'episode': 'episodes',
        'video': 'shortform',
    }

    def _real_extract(self, url):
        ptype, video_id = re.match(self._VALID_URL, url).groups()
        resp = self._download_json(
            'https://player.api.stv.tv/v1/%s/%s' % (self._PTYPE_MAP[ptype], video_id),
            video_id)

        result = resp['results']
        video = result['video']
        video_id = compat_str(video['id'])

        subtitles = {}
        _subtitles = result.get('_subtitles') or {}
        for ext, sub_url in _subtitles.items():
            subtitles.setdefault('en', []).append({
                'ext': 'vtt' if ext == 'webvtt' else ext,
                'url': sub_url,
            })

        programme = result.get('programme') or {}

        return {
            '_type': 'url_transparent',
            'id': video_id,
            'url': self.BRIGHTCOVE_URL_TEMPLATE % video_id,
            'description': result.get('summary'),
            'duration': float_or_none(video.get('length'), 1000),
            'subtitles': subtitles,
            'view_count': int_or_none(result.get('views')),
            'series': programme.get('name') or programme.get('shortName'),
            'ie_key': 'BrightcoveNew',
        }

@@ -169,16 +169,63 @@
 r_none,%0A
+    smuggle_url,%0A    str_or_none,%0A    try_get,%0A
 )%0A%0A%0Aclas
@@ -379,20 +379,42 @@
    _TEST
+S
  = 
-%7B
+%5B%7B%0A        # shortform
 %0A       
@@ -1018,16 +1018,159 @@
 ',%0A    %7D
+, %7B%0A        # episodes%0A        'url': 'https://player.stv.tv/episode/4125/jennifer-saunders-memory-lane',%0A        'only_matching': True,%0A    %7D%5D
 %0A    BRI
@@ -1460,24 +1460,25 @@
 roups()%0A
+%0A
         
 resp = s
@@ -1469,20 +1469,23 @@
         
-resp
+webpage
  = self.
@@ -1498,112 +1498,976 @@
 oad_
-json(%0A            'https://
+webpage(url, video_id, fatal=False) or ''%0A        props = (self._parse_json(self._search_regex(%0A            r'%3Cscript%5B%5E%3E%5D+id=%22__NEXT_DATA__%22%5B%5E%3E%5D*%3E(%7B.+?%7D)%3C/script%3E',%0A            webpage, 'next data', default='%7B%7D'), video_id,%0A            fatal=False) or %7B%7D).get('props') or %7B%7D%0A        player_api_cache = try_get(%0A            props, lambda x: x%5B'initialReduxState'%5D%5B'playerApiCache'%5D) or %7B%7D%0A%0A        api_path, resp = None, %7B%7D%0A        for k, v in 
 player
-.api.stv.tv/v1/%25s/%25s' %25 (self._PTYPE_MAP%5Bptype%5D, video_id),%0A           
+_api_cache.items():%0A            if k.startswith('/episodes/') or k.startswith('/shortform/'):%0A                api_path, resp = k, v%0A                break%0A        else:%0A            episode_id = str_or_none(try_get(%0A                props, lambda x: x%5B'pageProps'%5D%5B'episodeId'%5D))%0A            api_path = '/%25s/%25s' %25 (self._PTYPE_MAP%5Bptype%5D, episode_id or video_id)%0A%0A        result = resp.get('results')%0A        if not result:%0A            resp = self._download_json(%0A                'https://player.api.stv.tv/v1' + api_path,
  vid
@@ -2465,33 +2465,36 @@
 path, video_id)%0A
-%0A
+    
         result =
@@ -2510,16 +2510,17 @@
 sults'%5D%0A
+%0A
         
@@ -3023,16 +3023,28 @@
  'url': 
+smuggle_url(
 self.BRI
@@ -3067,32 +3067,60 @@
 LATE %25 video_id,
+ %7B'geo_countries': %5B'GB'%5D%7D),
 %0A            'de

improve episode id extraction(closes #23083)