"""Sylunara Signals client — for any bot, agent, or scraper.

Reads the live trading book and provides:
  - current_positions(): list of open positions across all venues
  - new_entries(prev_symbols): symbols that appeared since last check
  - closed_positions(prev_symbols): symbols that disappeared since last check
  - verify_chain(): check hash chain integrity
  - get_rules(): the trading rule set

Usage:
  from sylunara_client import SylunaraClient
  client = SylunaraClient()
  book = client.current_positions()
"""
import json
import hashlib
from urllib.request import urlopen, Request

FEED_URL = "https://sylunara-signals.crypto-guard.workers.dev"
TIMEOUT = 10
USER_AGENT = "SylunaraBot/1.0 (+https://sylunara.ai)"


class SylunaraClient:
    def __init__(self, base_url=FEED_URL):
        self.base = base_url.rstrip("/")
        self._last_book = None

    def _fetch(self, path="/signals.json"):
        req = Request(
            f"{self.base}{path}",
            headers={"Accept": "application/json", "User-Agent": USER_AGENT},
        )
        with urlopen(req, timeout=TIMEOUT) as r:
            return json.loads(r.read())

    def current_positions(self):
        snap = self._fetch("/signals.json")
        self._last_book = snap
        return snap.get("book", [])

    def new_entries(self, prev_symbols=None):
        book = self.current_positions()
        current = {p["symbol"] for p in book}
        if prev_symbols is None:
            return book
        return [p for p in book if p["symbol"] not in prev_symbols]

    def closed_positions(self, prev_symbols=None):
        book = self.current_positions()
        current = {p["symbol"] for p in book}
        if prev_symbols is None:
            return []
        return list(prev_symbols - current)

    def get_rules(self):
        return self._fetch("/rules.json")

    def get_manifest(self):
        return self._fetch("/agents.json")

    def verify_chain(self):
        return self._fetch("/head.json")

    def summary(self):
        book = self.current_positions()
        symbols = [p["symbol"] for p in book]
        return f"{len(book)} positions: {', '.join(symbols)}"


if __name__ == "__main__":
    c = SylunaraClient()
    book = c.current_positions()
    print(f"Sylunara live book -- {len(book)} positions:")
    for p in book:
        pl = p.get("unrealized_pct", 0) or 0
        arrow = "+" if pl >= 0 else ""
        sym = p.get("symbol", "?")
        direction = p.get("direction", "?")
        entry = p.get("entry_price", "?")
        held = p.get("held_hours", "?")
        mv = p.get("market_value_usd", 0)
        print(f"  {sym:8s} {direction:5s} entry={entry} held={held}h P/L={arrow}{pl}% mv=" + str(mv))
    print(f"Feed: {FEED_URL}")
    print(f"Manifest: {FEED_URL}/agents.json")
