import json
from datetime import datetime, timedelta
from calibre.web.feeds.recipes import BasicNewsRecipe
from contextlib import closing

class DailyOfficeSingle(BasicNewsRecipe):
    title       = 'The Daily Office Readings (Single Feed)'
    __author__  = 'Anglican Church in North America and Dunhill'
    description = 'ACNA Book of Common Prayer Daily Readings'
    language = 'en'

    days_number = 6
    daily_office_settings = '?absolution=lay&bible_translation=nasb&canticle_rotation=default&chrysostom=on&collects=rotating&confession=long-on-fast&ep_great_litany=ep_litany_off&family-creed=family-creed-no&family-opening-sentence=family-opening-sentence-fixed&family_collect=time_of_day&family_reading_audio=off&family_readings=brief&format=json&general_thanksgiving=on&grace=rotating&language_style=contemporary&language_style_for_our_father=traditional&lectionary=daily-office-readings&morning_prayer_invitatory=invitatory_traditional&mp_great_litany=mp_litany_off&national_holidays=us&o_antiphons=literal&psalm_style=whole_verse&psalm_translation=contemporary&psalms=contemporary&psalter=60&reading_audio=off&reading_cycle=1&reading_headings=on&reading_length=full&style=unison&suffrages=rotating&translation=nasb'

    def parse_index(self):
        today = datetime.now()
        articles = []

        for i in range(self.days_number):
            current_date = today + timedelta(days=i)
            date_str = current_date.strftime('%Y-%m-%d')
            url = f'https://api.dailyoffice2019.com/api/v1/readings/{date_str}{self.daily_office_settings}'
            day_title = current_date.strftime('Daily Prayer Readings for %B %d, %Y')

            with closing(self.browser.open_novisit(url, timeout=self.timeout)) as f:
                raw = f.read()
            json_data = json.loads(raw.decode('utf-8'))

            # Morning Prayer
            for item in json_data.get("services", {}).get("Morning Prayer", {}).get("readings", []):
                full = item.get("full", {})
                if full.get("cycle") != "30":
                    art_title = f"{day_title} – Morning Prayer – {full.get('name')}"
                    articles.append({'title': art_title, 'url': url})

            # Evening Prayer
            for item in json_data.get("services", {}).get("Evening Prayer", {}).get("readings", []):
                full = item.get("full", {})
                if full.get("cycle") != "30":
                    art_title = f"{day_title} – Evening Prayer – {full.get('name')}"
                    articles.append({'title': art_title, 'url': url})

        # A single feed with all articles
        return [(self.title, articles)]

    def preprocess_raw_html(self, raw_html, url):
        json_data = json.loads(raw_html)
        new_html_content = "<html><body>"

        # Morning Prayer
        new_html_content += "<h1>Morning Prayer</h1>"
        for item in json_data.get("services", {}).get("Morning Prayer", {}).get("readings", []):
            full = item.get("full", {})
            if full.get("cycle") != "30":
                new_html_content += f"<h2>{full.get('name')}</h2>{full.get('text','')}"

        # Evening Prayer
        new_html_content += "<h1>Evening Prayer</h1>"
        for item in json_data.get("services", {}).get("Evening Prayer", {}).get("readings", []):
            full = item.get("full", {})
            if full.get("cycle") != "30":
                new_html_content += f"<h2>{full.get('name')}</h2>{full.get('text','')}"

        new_html_content += "</body></html>"
        return new_html_content

