#!/usr/bin/env python3
"""Builds a one-page podcast site and its RSS feed from your Releases and episodes/*.md.

Used by .github/workflows/publish.yml. Only the Python standard library is needed.
"""
from __future__ import annotations

import argparse
import json
import re
import shutil
from datetime import datetime, timezone
from email.utils import format_datetime
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
LANGUAGE_CODES = {'english': 'en', 'spanish': 'es', 'portuguese': 'pt', 'french': 'fr', 'italian': 'it', 'hindi': 'hi', 'german': 'de'}


def setting(text: str, label: str, default: str) -> str:
    found = re.search(rf'^- {re.escape(label)}:[ \t]*(.+)$', text, flags=re.M)
    value = found.group(1).strip() if found else ''
    return value if value and not value.startswith('[') else default


def language_code(language: str) -> str:
    return next((code for name, code in LANGUAGE_CODES.items() if name in language.lower()), 'en')


def inline(text: str) -> str:
    out = escape(text)
    out = re.sub(r'\[([^\]]+)\]\((https?://[^)\s]+)\)', r'<a href="\2" rel="noopener">\1</a>', out)
    return re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', out)


def notes_html(markdown: str) -> str:
    html, in_list = [], False
    for line in markdown.splitlines():
        line = line.strip()
        item = re.match(r'^[-*]\s+(.*)', line)
        if in_list and not item:
            html.append('</ul>')
            in_list = False
        if item:
            if not in_list:
                html.append('<ul>')
                in_list = True
            html.append(f'<li>{inline(item.group(1))}</li>')
        elif line.startswith('#'):
            if not line.startswith('# '):
                html.append(f'<h3>{inline(line.lstrip("# "))}</h3>')
        elif line:
            html.append(f'<p>{inline(line)}</p>')
    if in_list:
        html.append('</ul>')
    return '\n'.join(html)


def episodes(releases: list[dict]) -> list[dict]:
    found = []
    for release in releases:
        match = re.fullmatch(r'ep-(\d{4}-\d{2}-\d{2})', release.get('tag_name', ''))
        audio = next((a for a in release.get('assets', []) if a['name'].endswith('.mp3')), None)
        if not match or not audio:
            continue
        day = match.group(1)
        path = ROOT / 'episodes' / f'{day}.md'
        text = path.read_text(encoding='utf-8') if path.exists() else release.get('body') or ''
        title = re.search(r'^# (.+)$', text, flags=re.M)
        found.append({'day': day, 'title': title.group(1).strip() if title else day, 'notes': notes_html(text),
                      'url': audio['browser_download_url'], 'bytes': audio['size']})
    return sorted(found, key=lambda e: e['day'], reverse=True)


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--releases', type=Path, required=True)
    ap.add_argument('--site-url', required=True)
    ap.add_argument('--out', type=Path, default=Path('dist'))
    args = ap.parse_args()

    briefing = ROOT / 'my-briefing.md'
    cfg = briefing.read_text(encoding='utf-8') if briefing.exists() else ''
    name = setting(cfg, 'Show name', 'My Briefing')
    lang = language_code(setting(cfg, 'Language', 'English'))
    about = setting(cfg, 'Audience', 'A daily news briefing.')
    email = setting(cfg, 'Feed email', '')
    site = args.site_url.rstrip('/')
    note = 'This episode was made with artificial intelligence from public sources. Check the original sources.'

    raw = args.releases.read_text(encoding='utf-8')
    # gh api --paginate can print several JSON lists one after another.
    releases, decoder, position = [], json.JSONDecoder(), 0
    while raw[position:].strip():
        position += len(raw[position:]) - len(raw[position:].lstrip())
        chunk, position = decoder.raw_decode(raw, position)
        releases.extend(chunk)
    items = episodes(releases)

    args.out.mkdir(parents=True, exist_ok=True)
    shutil.copy(ROOT / 'publish' / 'cover.png', args.out / 'cover.png')
    blocks = '\n'.join(
        f'<article><h2>{escape(e["title"])}</h2><p class="date">{e["day"]}</p>'
        f'<audio controls preload="none" src="{escape(e["url"], quote=True)}"></audio>'
        f'<details><summary>Stories and sources</summary>{e["notes"]}</details></article>' for e in items)
    (args.out / 'index.html').write_text(f'''<!doctype html>
<html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{escape(name)}</title><link rel="alternate" type="application/rss+xml" title="{escape(name, quote=True)}" href="{site}/feed.xml">
<style>body{{margin:0 auto;max-width:42rem;padding:3rem 1.25rem;font-family:Arial,Helvetica,sans-serif;line-height:1.55;background:#fff;color:#111}}
h1{{font-size:2.4rem;line-height:1.1}}article{{margin-top:3.5rem}}h2{{font-size:1.3rem;margin:0}}.date{{margin:.25rem 0 .75rem;color:#555}}
audio{{width:100%}}summary{{cursor:pointer;margin-top:.75rem}}a{{color:inherit}}</style></head>
<body><h1>{escape(name)}</h1><p>{escape(about)}</p><p><a href="feed.xml">Podcast feed (RSS)</a></p>
{blocks or "<p>The first episode is on its way.</p>"}
<p class="date">{note}</p></body></html>
''', encoding='utf-8')

    entries = []
    for e in items:
        published = datetime.strptime(e['day'], '%Y-%m-%d').replace(hour=6, tzinfo=timezone.utc)
        entries.append(
            f'<item><title>{escape(e["title"])}</title><guid isPermaLink="false">ep-{e["day"]}</guid>'
            f'<pubDate>{format_datetime(published)}</pubDate>'
            f'<enclosure url="{escape(e["url"], quote=True)}" length="{e["bytes"]}" type="audio/mpeg"/>'
            f'<description>{escape(e["notes"] + "<p>" + note + "</p>")}</description></item>')
    owner = f'<itunes:owner><itunes:email>{escape(email)}</itunes:email></itunes:owner>' if email else ''
    (args.out / 'feed.xml').write_text(
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"><channel>'
        f'<title>{escape(name)}</title><link>{site}/</link><language>{lang}</language>'
        f'<description>{escape(about)}</description><itunes:author>{escape(name)}</itunes:author>'
        f'<itunes:image href="{site}/cover.png"/><itunes:category text="News"/><itunes:explicit>false</itunes:explicit>{owner}'
        + ''.join(entries) + '</channel></rss>\n', encoding='utf-8')
    print(f'Built {len(items)} episodes into {args.out}')


if __name__ == '__main__':
    main()
