"""
Sylunara Signals Connector for Hummingbot
Polls the Sylunara signals feed and logs when the book updates.

Setup:
  1. Place in hummingbot/scripts/
  2. Run: start --script sylunara_connector.py
  3. Configure your connector to trade the pairs Sylunara publishes

Feed: https://sylunara-signals.crypto-guard.workers.dev/signals.json
Free, public, hash-chained. Disclosure, not advice.
"""

import json
import time
from urllib.request import urlopen

FEED_URL = "https://sylunara-signals.crypto-guard.workers.dev/signals.json"
POLL_INTERVAL = 900


class SylunaraConnector:
    def __init__(self, markets, order_amount_usd=50):
        self.markets = markets
        self.order_amount = order_amount_usd

    def fetch_book(self):
        try:
            resp = urlopen(FEED_URL, timeout=10)
            return json.loads(resp.read())
        except Exception as e:
            print(f"Error fetching feed: {e}")
            return None

    def get_signals(self):
        book = self.fetch_book()
        if not book:
            return []
        signals = []
        for pos in book.get("book", []):
            if pos["direction"] == "long":
                signals.append({
                    "pair": pos["symbol"],
                    "entry": pos["entry_price"],
                    "held_hours": pos["held_hours"],
                    "unrealized_pct": pos["unrealized_pct"],
                })
        return signals

    def run(self):
        while True:
            signals = self.get_signals()
            long_pairs = {s["pair"] for s in signals}
            print(f"[{time.strftime('%H:%M:%S')}] Sylunara long: {long_pairs}")
            time.sleep(POLL_INTERVAL)


if __name__ == "__main__":
    c = SylunaraConnector(markets=["BTC/USD", "SOL/USD", "UNI/USD"])
    c.run()
