#!/usr/bin/env python
# vim:fileencoding=utf-8
"""
https://www.cirsd.org/en/horizons
"""

from calibre.web.feeds.news import BasicNewsRecipe, classes


class horizons(BasicNewsRecipe):
    title = 'Horizons'
    __author__ = 'unkn0wn'
    description = (
        ' Horizons – Journal of International Relations and Sustainable Development.'
        ' Horizons serves as a high-level platform for influential voices from around the world to'
        ' provide informed analysis and conduct reasoned exchanges on the full spectrum of issues'
        ' that shape international developments.'
    )
    no_stylesheets = True
    use_embedded_content = False
    encoding = 'utf-8'
    language = 'en'
    remove_attributes = ['style', 'height', 'width']
    masthead_url = 'https://www.cirsd.org/bundles/olpublic/images/horizons-logo.jpg'
    ignore_duplicate_articles = {'url'}
    extra_css = 'em{color:#202020;}'
    simultaneous_downloads = 1

    remove_tags_before = [dict(name='div', **classes('e-con-boxed'))]
    remove_tags_after = [dict(name='div', **classes('e-con-boxed'))]

    recipe_specific_options = {
        'issue_url': {
            'short': 'The issue URL ',
            'long': 'For example, https://www.cirsd.org/en/horizons/horizons-winter-2024--issue-no-25',
        }
    }

    def preprocess_html(self, soup):
        div = soup.find('div', **classes('e-con-boxed'))
        child = div.find('div', **classes('e-child'))
        if child:
            soup.body.clear()
            soup.body.append(child)
        return soup

    def preprocess_raw_html(self, raw, *a):
        return raw.replace('<p>&nbsp;</p>', '').replace('<p dir="ltr">&nbsp;</p>', '')

    def parse_index(self):
        d = self.recipe_specific_options.get('issue_url')
        if d and isinstance(d, str):
            url = d
        else:
            soup = self.index_to_soup('https://www.cirsd.org/en/horizons')
            div = soup.find('div', **classes('horizon-issue'))
            for a in div.findAll('a', href=True):
                if a.find('img'):
                    url = a['href']
                    if url.startswith('/'):
                        url = 'https://www.cirsd.org' + url
                    self.cover_url = a.find('img')['src']
                    self.log(url, '\n', self.cover_url)
        self.title = url.split('/')[-2].replace('-', ' ').title()
        self.log('Downloading Issue: ', self.title)

        soup = self.index_to_soup(url)
        toc = soup.find('div', attrs={'class': 'horizon-toc'})
        feeds = []
        for section in toc.findAll('div', attrs={'class': 'horizon-section'}):
            secname = self.tag_to_string(section.h3).strip()
            self.log(secname)
            articles = []
            ul = section.find('ul', attrs={'class': 'horizon-articles-list'})
            for a in ul.findAll('a', href=True):
                url = a['href']
                if url.startswith('/'):
                    url = 'https://www.cirsd.org' + url
                title = self.tag_to_string(a)
                desc = ''
                span = a.find_next_sibling('span', attrs={'class': 'article-author'})
                if span:
                    desc = self.tag_to_string(span).strip()
                self.log('\t', title, '\n\t', desc, '\n\t\t', url)
                articles.append({'title': title, 'url': url, 'description': desc})
            if articles:
                feeds.append((secname, articles))
        return feeds
