#!/usr/bin/env python3

import feedparser
import json
import os

cache_dir = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
title_file = os.path.join(cache_dir, "arch_news_last_title")
url_file = os.path.join(cache_dir, "arch_news_last_url")
read_file = os.path.join(cache_dir, "arch_news_read")

feed_url = "https://archlinux.org/feeds/news/"

def fetch_latest_news():
    try:
        feed = feedparser.parse(feed_url)
        if not feed.entries:
            return {"text": "", "tooltip": "", "class": ""}

        latest = feed.entries[0]
        title = latest.title.strip()
        link = latest.link.strip()

        # Guardar título y URL de la última noticia
        os.makedirs(cache_dir, exist_ok=True)
        with open(title_file, "w") as f:
            f.write(title)
        with open(url_file, "w") as f:
            f.write(link)

        # Leer la última noticia leída
        read_title = ""
        if os.path.exists(read_file):
            with open(read_file, "r") as f:
                read_title = f.read().strip()

        if title == read_title:
            return {"text": "", "tooltip": "", "class": ""}

        return {
            "text": "NEWS",
            "tooltip": title,
            "class": "news-alert"
        }

    except Exception as e:
        return {
            "text": "NEWS",
            "tooltip": "Error al obtener noticias",
            "class": "error"
        }

if __name__ == "__main__":
    print(json.dumps(fetch_latest_news()))

