#!/usr/bin/env python3
import argparse
import asyncio
import html
import json
import os
import sys
import time

import aiohttp
import feedparser
import nio
import toml

CONFIG_DEFAULT = "/etc/matrix-rss/config.toml"
STATE_DIR = "/var/lib/matrix-rss"


def load_config(path):
    data = toml.load(path)
    cfg = {}
    for key in ("homeserver", "username", "domain", "password", "access_token", "interval", "slo_time_to_run", "prometheus_port", "feed_path"):
        if key in data:
            cfg[key] = data[key]
    if "mgmt_rooms" in data:
        cfg["mgmt_rooms"] = data["mgmt_rooms"]
    return cfg


def load_bridges(path):
    data = toml.load(path)
    bridges = []
    for entry in data.get("bridge", []):
        bridges.append(entry)
    return bridges


def render_template(template, entry):
    ctx = {
        "title": entry.get("title", ""),
        "link": entry.get("link", ""),
        "published": entry.get("published", entry.get("updated", "")),
        "author": entry.get("author", ""),
        "summary": entry.get("summary", ""),
        "nl": "\n\n",
    }
    out = template
    for key, value in ctx.items():
        out = out.replace("{{%s}}" % key, html.escape(str(value)))
    return out


def state_file(name):
    safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in name)
    return os.path.join(STATE_DIR, safe + "_entries.json")


def load_seen(path):
    if os.path.isfile(path):
        with open(path, "r", encoding="utf-8") as f:
            return set(json.load(f))
    return set()


def save_seen(path, seen):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(sorted(seen), f)


async def post_to_room(client, cfg, room_id, text):
    content = {
        "msgtype": "m.text",
        "body": text,
        "format": "org.matrix.custom.html",
        "formatted_body": text,
    }
    token = cfg.get("access_token", "")
    hs = cfg.get("homeserver", "").rstrip("/")
    txn = "rss_%d" % int(time.time() * 1000)
    url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s" % (hs, room_id, txn)
    headers = {"Authorization": "Bearer " + token}
    for _ in range(4):
        async with aiohttp.ClientSession() as sess:
            async with sess.put(url, json=content, headers=headers) as resp:
                if resp.status == 429:
                    await asyncio.sleep(5)
                    continue
                body = await resp.json()
                if resp.status == 200 and body.get("event_id"):
                    return True
                raise RuntimeError("send failed %d: %s" % (resp.status, body))
    raise RuntimeError("ratelimited after retries")


async def check_feed(client, cfg, bridge):
    url = bridge.get("feed_url", "")
    room = bridge.get("room_id", "")
    name = bridge.get("name", url)
    if not url or not room:
        return
    state = state_file(name)
    seen = load_seen(state)
    d = feedparser.parse(url)
    new = []
    for entry in d.entries:
        eid = entry.get("id") or entry.get("link")
        if eid is None:
            continue
        if eid in seen:
            continue
        new.append((eid, entry))
    if not new:
        return
    tmpl = bridge.get("template_markdown", "<h2><a href=\"{{link}}\">{{title}}</a></h2>\n\n{{author}}\n{{published}}\n{{summary}}")
    for eid, entry in new:
        text = render_template(tmpl, entry)
        try:
            await post_to_room(client, cfg, room, text)
            seen.add(eid)
        except Exception as exc:
            print("post failed for %s: %s" % (name, exc), file=sys.stderr)
            break
        save_seen(state, seen)
        await asyncio.sleep(20)
    save_seen(state, seen)


def add_feed_to_config(config_path, name, url, room_id):
    import toml as _toml
    data = _toml.load(config_path)
    for b in data.get("bridge", []):
        if b.get("name") == name:
            return False, "feed %s already exists" % name
    data.setdefault("bridge", []).append({"name": name, "feed_url": url, "room_id": room_id})
    with open(config_path, "w", encoding="utf-8") as f:
        _toml.dump(data, f)
    return True, None


async def handle_command(client, cfg, config_path, room_id, text):
    parts = text.strip().split()
    if not parts:
        return
    cmd = parts[0].lower()
    if cmd == "!rss" and len(parts) >= 3 and parts[1].lower() == "add":
        name = parts[2]
        if len(parts) < 4:
            await post_to_room(client, cfg, room_id, "<b>usage:</b> !rss add &lt;name&gt; &lt;feed-url&gt; [room-id]")
            return
        url = parts[3]
        target = room_id
        if len(parts) >= 5:
            target = parts[4]
        ok, err = add_feed_to_config(config_path, name, url, target)
        if not ok:
            await post_to_room(client, cfg, room_id, "<b>error:</b> " + html.escape(err))
            return
        bridge = {"name": name, "feed_url": url, "room_id": target, "template_markdown": "{{title}}{{nl}}{{nl}}{{author}} ({{published}}){{nl}}{{nl}}{{summary}}{{nl}}{{nl}}{{link}}{{nl}}"}
        try:
            await check_feed(client, cfg, bridge)
            await post_to_room(client, cfg, room_id, "<b>added feed</b> %s into %s" % (html.escape(name), html.escape(target)))
        except Exception as exc:
            await post_to_room(client, cfg, room_id, "<b>added, but first check failed:</b> " + html.escape(str(exc)))
    elif cmd == "!rss" and len(parts) >= 2 and parts[1].lower() == "list":
        bridges = load_bridges(config_path)
        lines = []
        for b in bridges:
            lines.append("<b>%s</b> - %s -> %s" % (html.escape(b.get("name", "?")), html.escape(b.get("feed_url", "")), html.escape(b.get("room_id", ""))))
        body = "Feeds:<br>" + "<br>".join(lines) if lines else "no feeds"
        await post_to_room(client, cfg, room_id, body)


def cmd_state_file():
    return os.path.join(STATE_DIR, "processed_commands.json")


def load_cmd_state():
    path = cmd_state_file()
    if os.path.isfile(path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                return set(json.load(f))
        except Exception:
            return set()
    return set()


def save_cmd_state(processed):
    with open(cmd_state_file(), "w", encoding="utf-8") as f:
        json.dump(sorted(processed), f)


async def event_loop(client, cfg, config_path, bridges):
    processed = load_cmd_state()
    while True:
        for room_id in list(cfg.get("mgmt_rooms", [])):
            try:
                resp2 = await client.room_messages(room_id, limit=15)
                chunk = getattr(resp2, "chunk", [])
                for event in chunk:
                    if isinstance(event, nio.RoomMessageText):
                        eid = getattr(event, "event_id", "")
                        if eid in processed:
                            continue
                        body = getattr(event, "body", "") or getattr(getattr(event, "content", None), "body", "")
                        if body.startswith("!rss"):
                            processed.add(eid)
                            save_cmd_state(processed)
                            print("got mgmt command: %s" % body, flush=True)
                            await handle_command(client, cfg, config_path, room_id, body)
            except Exception as exc:
                print("mgmt poll error %s: %s" % (room_id, exc), flush=True)
        try:
            resp = await client.sync(timeout=15000)
        except Exception as exc:
            print("sync error: %s" % exc, file=sys.stderr)
            await asyncio.sleep(5)
            continue
        for room_id, room in resp.rooms.join.items():
            for event in room.timeline.events:
                if isinstance(event, nio.RoomMessageText):
                    eid = getattr(event, "event_id", "")
                    if eid in processed:
                        continue
                    body = getattr(event, "body", "") or getattr(getattr(event, "content", None), "body", "")
                    if body.startswith("!rss"):
                        processed.add(eid)
                        save_cmd_state(processed)
                        print("got command: %s in %s" % (body, room_id), flush=True)
                        try:
                            await handle_command(client, cfg, config_path, room_id, body)
                        except Exception as exc:
                            print("rss cmd error: %s" % exc, file=sys.stderr)


async def run(cfg, bridges, config_path):
    client = nio.AsyncClient(cfg.get("homeserver", "http://127.0.0.1:8008"))
    if "access_token" in cfg:
        client.access_token = cfg.get("access_token")
    if "user_id" in cfg:
        client.user_id = cfg.get("user_id")
    elif "username" in cfg:
        client.user_id = "@%s:%s" % (cfg.get("username"), cfg.get("domain", "marlonivo.com"))
    interval = int(cfg.get("interval", 300))
    for bridge in bridges:
        try:
            await check_feed(client, cfg, bridge)
        except Exception as exc:
            print("feed error %s: %s" % (bridge.get("name", "?"), exc), file=sys.stderr)
    loop_task = asyncio.create_task(event_loop(client, cfg, config_path, bridges))
    while True:
        await asyncio.sleep(interval)
        for bridge in bridges:
            try:
                await check_feed(client, cfg, bridge)
            except Exception as exc:
                print("feed error %s: %s" % (bridge.get("name", "?"), exc), file=sys.stderr)


def main():
    ap = argparse.ArgumentParser(description="RSS to Matrix bridge")
    ap.add_argument("-c", "--config", default=CONFIG_DEFAULT)
    ap.add_argument("--once", action="store_true", help="check feeds once and exit")
    ap.add_argument("--test-feed", metavar="URL")
    args = ap.parse_args()
    if args.test_feed:
        d = feedparser.parse(args.test_feed)
        print("feed:", d.feed.get("title", "?"))
        for e in d.entries[:5]:
            print(" - %s | %s" % (e.get("title", "")[:60], e.get("published", e.get("updated", ""))[:20]))
        return 0
    cfg = load_config(args.config)
    bridges = load_bridges(args.config)
    if not os.path.isdir(STATE_DIR):
        os.makedirs(STATE_DIR)
    if not bridges:
        print("no feeds configured", file=sys.stderr)
        return 1
    asyncio.run(run(cfg, bridges, args.config))
    return 0


if __name__ == "__main__":
    sys.exit(main())