#!/usr/bin/env python3
"""Bell Feed RSS 2.0 生成器 — 從 summaries.json 生成 feed.xml"""

import json
from datetime import datetime
from email.utils import format_datetime
from pathlib import Path
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, ElementTree, indent

OUTPUT_DIR = Path(__file__).parent / "output"
FEED_URL = "https://data.degendar.com/feed.xml"
SITE_URL = "https://degendar.com"
BELL_NS = "https://degendar.com/ns/bell/1.0"

ET.register_namespace("bell", BELL_NS)
ET.register_namespace("atom", "http://www.w3.org/2005/Atom")


def generate_feed(summaries_path: Path | None = None, output_path: Path | None = None):
    summaries_path = summaries_path or OUTPUT_DIR / "summaries.json"
    output_path = output_path or OUTPUT_DIR / "feed.xml"

    if not summaries_path.exists():
        print(f"ERROR: {summaries_path} not found")
        return

    summaries = json.loads(summaries_path.read_text(encoding="utf-8"))

    rss = Element("rss", version="2.0")

    channel = SubElement(rss, "channel")
    SubElement(channel, "title").text = "Bell Feed — Crypto Twitter Intelligence"
    SubElement(channel, "link").text = SITE_URL
    SubElement(channel, "description").text = (
        "AI-curated crypto Twitter summaries from bell notification accounts"
    )
    SubElement(channel, "language").text = "zh-TW"

    atom_link = SubElement(channel, "{http://www.w3.org/2005/Atom}link")
    atom_link.set("href", FEED_URL)
    atom_link.set("rel", "self")
    atom_link.set("type", "application/rss+xml")

    if summaries:
        ts = summaries[0].get("timestamp", "")
        if ts:
            try:
                dt = datetime.fromisoformat(ts)
                SubElement(channel, "lastBuildDate").text = format_datetime(dt)
            except ValueError:
                pass

    for entry in summaries[:50]:
        item = SubElement(channel, "item")

        title_text = entry.get("summary_text", "")[:120]
        if len(entry.get("summary_text", "")) > 120:
            title_text += "…"
        SubElement(item, "title").text = title_text or entry.get("id", "Summary")

        entry_id = entry.get("id", "")
        SubElement(item, "link").text = f"{SITE_URL}#summary-{entry_id}"
        SubElement(item, "guid").text = f"bell-feed:{entry_id}"

        ts = entry.get("timestamp", "")
        if ts:
            try:
                dt = datetime.fromisoformat(ts)
                SubElement(item, "pubDate").text = format_datetime(dt)
            except ValueError:
                pass

        description_parts = []
        if entry.get("summary_text"):
            description_parts.append(entry["summary_text"])
        if entry.get("signals"):
            description_parts.append(f"\n\nTrading Signals:\n{entry['signals']}")
        SubElement(item, "description").text = "\n".join(description_parts)

        tokens = entry.get("tokens", [])
        if tokens:
            SubElement(item, f"{{{BELL_NS}}}tokens").text = ",".join(tokens)

        if entry.get("signals"):
            SubElement(item, f"{{{BELL_NS}}}signals").text = entry["signals"]

        SubElement(item, f"{{{BELL_NS}}}tweetCount").text = str(
            entry.get("tweet_count", 0)
        )

        for contract in entry.get("contracts", []):
            SubElement(item, f"{{{BELL_NS}}}contract").text = contract

    indent(rss, space="  ")
    tree = ElementTree(rss)
    tree.write(output_path, encoding="unicode", xml_declaration=True)

    print(f"✓ RSS feed 已生成: {output_path} ({len(summaries[:50])} items)")


if __name__ == "__main__":
    generate_feed()
