#!/usr/bin/env  python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>

import json
from collections import defaultdict
from datetime import datetime, timedelta
import time

from calibre import replace_entities
from calibre.ptempfile import PersistentTemporaryFile
from calibre.ebooks.BeautifulSoup import NavigableString, Tag
from calibre.utils.date import parse_only_date
from calibre.web.feeds.news import BasicNewsRecipe
from html5_parser import parse
from lxml import etree

# For past editions, set date to, for example, '2020-11-28'
edition_date = None


def E(parent, name, text='', **attrs):
    ans = parent.makeelement(name, **attrs)
    ans.text = text
    parent.append(ans)
    return ans


def process_node(node, html_parent):
    ntype = node.get('type')
    if ntype == 'tag':
        c = html_parent.makeelement(node['name'])
        c.attrib.update({k: v or '' for k, v in node.get('attribs', {}).items()})
        html_parent.append(c)
        for nc in node.get('children', ()):
            process_node(nc, c)
    elif ntype == 'text':
        text = node.get('data')
        if text:
            text = replace_entities(text)
            if len(html_parent):
                t = html_parent[-1]
                t.tail = (t.tail or '') + text
            else:
                html_parent.text = (html_parent.text or '') + text


def safe_dict(data, *names):
    ans = data
    for x in names:
        ans = ans.get(x) or {}
    return ans


class JSONHasNoContent(ValueError):
    pass


def load_article_from_json(raw, root):
    # open('/t/raw.json', 'w').write(raw)
    data = json.loads(raw)
    body = root.xpath('//body')[0]
    article = E(body, 'article')
    E(article, 'div', data['flyTitle'] , style='color: red; font-size:small; font-weight:bold;')
    E(article, 'h1', data['title'], title=safe_dict(data, "url", "canonical") or '')
    E(article, 'div', data['rubric'], style='font-style: italic; color:#202020;')
    try:
        date = data['dateModified']
    except:
        date = data['datePublished']
    dt = datetime.fromisoformat(date[:-1]) + timedelta(seconds=time.timezone)
    dt = dt.strftime('%b %d, %Y, %I:%M %p')
    if data['dateline'] is None:
        E(article, 'p', dt, style='color: gray; font-size:small;')
    else:
        E(article, 'p', dt + ' | ' + (data['dateline']), style='color: gray; font-size:small;')
    main_image_url = safe_dict(data, 'image', 'main', 'url').get('canonical')
    if main_image_url:
        div = E(article, 'div')
        try:
            E(div, 'img', src=main_image_url)
        except Exception:
            pass
    for node in data.get('text') or ():
        process_node(node, article)


def cleanup_html_article(root):
    main = root.xpath('//main')[0]
    body = root.xpath('//body')[0]
    for child in tuple(body):
        body.remove(child)
    body.append(main)
    main.set('id', '')
    main.tag = 'article'
    for x in root.xpath('//*[@style]'):
        x.set('style', '')
    for x in root.xpath('//button'):
        x.getparent().remove(x)


def classes(classes):
    q = frozenset(classes.split(' '))
    return dict(attrs={
        'class': lambda x: x and frozenset(x.split()).intersection(q)})


def new_tag(soup, name, attrs=()):
    impl = getattr(soup, 'new_tag', None)
    if impl is not None:
        return impl(name, attrs=dict(attrs))
    return Tag(soup, name, attrs=attrs or None)


class NoArticles(Exception):
    pass


def process_url(url):
    if url.startswith('/'):
        url = 'https://www.economist.com' + url
    return url


class Economist(BasicNewsRecipe):

    title = 'The Economist'
    language = 'en'
    encoding = 'utf-8'
    masthead_url = 'https://www.livemint.com/lm-img/dev/economist-logo-oneline.png'

    __author__ = "Kovid Goyal"
    description = (
        'Global news and current affairs from a European'
        ' perspective. Best downloaded on Friday mornings (GMT)'
    )
    extra_css = '''
        em { color:#202020; }
        img {display:block; margin:0 auto;}
    '''
    oldest_article = 7.0
    resolve_internal_links = True
    remove_tags = [
        dict(name=['script', 'noscript', 'title', 'iframe', 'cf_floatingcontent', 'aside', 'footer']),
        dict(attrs={'aria-label': "Article Teaser"}),
        dict(attrs={
                'class': [
                    'dblClkTrk', 'ec-article-info', 'share_inline_header',
                    'related-items', 'main-content-container', 'ec-topic-widget',
                    'teaser', 'blog-post__bottom-panel-bottom', 'blog-post__comments-label',
                    'blog-post__foot-note', 'blog-post__sharebar', 'blog-post__bottom-panel',
                    'newsletter-form','share-links-header','teaser--wrapped', 'latest-updates-panel__container',
                    'latest-updates-panel__article-link','blog-post__section'
                ]
            }
        ),
        dict(attrs={
                'class': lambda x: x and 'blog-post__siblings-list-aside' in x.split()}),
        classes(
            'share-links-header teaser--wrapped latest-updates-panel__container'
            ' latest-updates-panel__article-link blog-post__section newsletter-form blog-post__bottom-panel'
        )
    ]
    keep_only_tags = [dict(name='article', id=lambda x: not x)]

    def preprocess_html(self, soup):
        for img in soup.findAll('img', src=True):
            img['src'] = img['src'].replace('www.economist.com/', 
                'www.economist.com/cdn-cgi/image/width=600,quality=80,format=auto/')
        return soup

    no_stylesheets = True
    remove_attributes = ['data-reactid', 'width', 'height']

    needs_subscription = False

    def get_browser(self, *args, **kwargs):
        # Needed to bypass cloudflare
        kwargs['user_agent'] = 'common_words/based'
        br = BasicNewsRecipe.get_browser(self, *args, **kwargs)
        br.addheaders += [('Accept-Language', 'en-GB,en-US;q=0.9,en;q=0.8')]
        return br

    def preprocess_raw_html(self, raw, url):
        body = '<html><body><article></article></body></html>'
        root = parse(body)
        load_article_from_json(raw, root)
        for div in root.xpath('//div[@class="lazy-image"]'):
            noscript = list(div.iter('noscript'))
            if noscript and noscript[0].text:
                img = list(parse(noscript[0].text).iter('img'))
                if img:
                    p = noscript[0].getparent()
                    idx = p.index(noscript[0])
                    p.insert(idx, p.makeelement('img', src=img[0].get('src')))
                    p.remove(noscript[0])
        for x in root.xpath('//*[name()="script" or name()="style" or name()="source" or name()="meta"]'):
            x.getparent().remove(x)
        # the economist uses <small> for small caps with a custom font
        for init in root.xpath('//span[@data-caps="initial"]'):
            init.set('style', 'font-weight:bold;')
        for x in root.xpath('//small'):
            if x.text and len(x) == 0:
                x.text = x.text.upper()
                x.tag = 'span'
                x.set('style', 'font-variant: small-caps')
        for h2 in root.xpath('//h2'):
            h2.tag = 'h4'
        for x in root.xpath('//figcaption'):
            x.set('style', 'text-align:center; font-size:small;')
        for x in root.xpath('//cite'):
            x.tag = 'blockquote'
            x.set('style', 'color:#404040;')
        raw = etree.tostring(root, encoding='unicode')
        return raw

    def publication_date(self):
        if edition_date:
            return parse_only_date(edition_date, as_utc=False)
        url = self.browser.open("https://www.economist.com/printedition").geturl()
        return parse_only_date(url.split("/")[-1], as_utc=False)

    def parse_index(self):
        soup = self.index_to_soup('https://www.economist.com/weeklyedition/archive')
        script_tag = soup.find("script", id="__NEXT_DATA__")
        if script_tag is not None:
            data = json.loads(script_tag.string)
            content_id = data['props']['pageProps']['content']['id'].split('/')[-1]

        url = 'https://cp2-graphql-gateway.p.aws.economist.com/graphql?query=query%20LatestWeeklyAutoEditionQuery(%24ref%3AString!)%7Bcanonical(ref%3A%24ref)%7BhasPart(from%3A0%20size%3A1%20sort%3A%22datePublished%3Adesc%22)%7Bparts%7B...WeeklyEditionFragment%20__typename%7D__typename%7D__typename%7D%7Dfragment%20WeeklyEditionFragment%20on%20Content%7Bid%20type%20datePublished%20image%7B...ImageCoverFragment%20__typename%7Durl%7Bcanonical%20__typename%7DhasPart(size%3A100%20sort%3A%22publication.context.position%22)%7Bparts%7B...ArticleFragment%20__typename%7D__typename%7D__typename%7Dfragment%20ArticleFragment%20on%20Content%7Bad%7Bgrapeshot%7Bchannels%7Bname%20__typename%7D__typename%7D__typename%7DarticleSection%7Binternal%7Bid%20title%3Aheadline%20__typename%7D__typename%7Daudio%7Bmain%7Bid%20duration(format%3A%22seconds%22)source%3Achannel%7Bid%20__typename%7Durl%7Bcanonical%20__typename%7D__typename%7D__typename%7Dbyline%20dateline%20dateModified%20datePublished%20dateRevised%20flyTitle%3Asubheadline%20id%20image%7B...ImageInlineFragment%20...ImageMainFragment%20...ImagePromoFragment%20__typename%7Dprint%7Btitle%3Aheadline%20flyTitle%3Asubheadline%20rubric%3Adescription%20section%7Bid%20title%3Aheadline%20__typename%7D__typename%7Dpublication%7Bid%20tegID%20title%3Aheadline%20flyTitle%3Asubheadline%20datePublished%20regionsAllowed%20url%7Bcanonical%20__typename%7D__typename%7Drubric%3Adescription%20source%3Achannel%7Bid%20__typename%7DtegID%20text(format%3A%22json%22)title%3Aheadline%20type%20url%7Bcanonical%20__typename%7Dtopic%20contentIdentity%7BforceAppWebview%20mediaType%20articleType%20__typename%7D__typename%7Dfragment%20ImageInlineFragment%20on%20Media%7Binline%7Burl%7Bcanonical%20__typename%7Dwidth%20height%20__typename%7D__typename%7Dfragment%20ImageMainFragment%20on%20Media%7Bmain%7Burl%7Bcanonical%20__typename%7Dwidth%20height%20__typename%7D__typename%7Dfragment%20ImagePromoFragment%20on%20Media%7Bpromo%7Burl%7Bcanonical%20__typename%7Did%20width%20height%20__typename%7D__typename%7Dfragment%20ImageCoverFragment%20on%20Media%7Bcover%7Bheadline%20width%20height%20url%7Bcanonical%20__typename%7DregionsAllowed%20__typename%7D__typename%7D&operationName=LatestWeeklyAutoEditionQuery&variables=%7B%22ref%22%3A%22%2Fcontent%2F{}%22%7D'
        url = url.format(content_id)

        raw = self.index_to_soup(url, raw=True)
        ans = self.economist_parse_index(raw)
        if not ans:
            raise NoArticles(
                'Could not find any articles, either the '
                'economist.com server is having trouble and you should '
                'try later or the website format has changed and the '
                'recipe needs to be updated.'
            )
        return ans

    def economist_parse_index(self, soup):
        data = json.loads(soup)['data']['canonical']['hasPart']['parts'][0]
        self.description = data['image']['cover'][0]['headline']
        dt = datetime.fromisoformat(data['datePublished'][:-1]) + timedelta(seconds=time.timezone)
        dt = dt.strftime('%b %d, %Y')
        self.timefmt = ' [' + dt + ']'
        self.cover_url = data['image']['cover'][0]['url']['canonical'].replace('www.economist.com/', 
            'www.economist.com/cdn-cgi/image/width=960,quality=80,format=auto/')
        self.log('Got cover:', self.cover_url)

        feeds_dict = defaultdict(list)
        for part in safe_dict(data, "hasPart", "parts"):
            try:
                section = part['articleSection']['internal'][0]['title']
            except:
                section = safe_dict(part, 'print', 'section', 'title') or 'section'
            title = safe_dict(part, "title")
            desc = safe_dict(part, "rubric") or ''
            sub = safe_dict(part, "flyTitle") or ''
            if sub and section != sub:
                desc = sub + ' :: ' + desc
            pt = PersistentTemporaryFile('.html')
            pt.write(json.dumps(part).encode('utf-8'))
            pt.close()
            url = 'file:///' + pt.name
            feeds_dict[section].append({"title": title, "url": url, "description": desc})
            self.log('\t', title, '\n\t', desc)
        return [(section, articles) for section, articles in feeds_dict.items()]

    def eco_find_image_tables(self, soup):
        for x in soup.findAll('table', align=['right', 'center']):
            if len(x.findAll('font')) in (1, 2) and len(x.findAll('img')) == 1:
                yield x

    def postprocess_html(self, soup, first):
        for img in soup.findAll('img', srcset=True):
            del img['srcset']
        for table in list(self.eco_find_image_tables(soup)):
            caption = table.find('font')
            img = table.find('img')
            div = new_tag(soup, 'div')
            div['style'] = 'text-align:left;font-size:70%'
            ns = NavigableString(self.tag_to_string(caption))
            div.insert(0, ns)
            div.insert(1, new_tag(soup, 'br'))
            del img['width']
            del img['height']
            img.extract()
            div.insert(2, img)
            table.replaceWith(div)
        return soup

    def canonicalize_internal_url(self, url, is_link=True):
        if url.endswith('/print'):
            url = url.rpartition('/')[0]
        return BasicNewsRecipe.canonicalize_internal_url(self, url, is_link=is_link)

    def populate_article_metadata(self, article, soup, first):
        article.url = soup.find('h1')['title']
