"""TikPlays developer API — build your own interactive in 60 lines.

A countdown that your viewers control. Every gift adds time, every follow adds a
little, and the remaining time is written to timer.txt so OBS can show it live.

    pip install websocket-client
    python 02_gift_timer.py YOUR_DEV_KEY

Then in OBS: add a Text source, tick "Read from file", and point it at timer.txt.

This is the whole pattern for any interactive you want to build:

    1. connect          2. read events in a loop
    3. decide what each event is worth      4. do your thing

Swap step 4 for anything — move a character, play a sound, fire a webhook at your
own game. The event stream is the only part that has to look like this.
"""
import json
import sys
import threading
import time

import websocket

DEV_KEY = (sys.argv[1] if len(sys.argv) > 1 else "").strip() or "PASTE_YOUR_DEV_KEY"
URL = f"wss://tiktok.shibalabs.live/ws/events?k={DEV_KEY}"

START_SECONDS = 5 * 60
SECONDS_PER_COIN = 1.0      # a 1-coin Rose adds 1 second, a 500-coin gift adds 500
SECONDS_PER_FOLLOW = 15
OUTPUT_FILE = "timer.txt"

deadline = time.time() + START_SECONDS
lock = threading.Lock()


def add_time(seconds, reason):
    global deadline
    with lock:
        # Extend from whichever is later: adding to a dead timer should restart it
        # from now, not from a deadline that passed ten minutes ago.
        deadline = max(deadline, time.time()) + seconds
        left = deadline - time.time()
    print(f"+{seconds:>4.0f}s  {reason:<40} ({left / 60:.1f} min left)")


def write_timer_file():
    """OBS reads this file a few times a second. Keep it dead simple."""
    while True:
        with lock:
            left = max(0, deadline - time.time())
        mins, secs = divmod(int(left), 60)
        try:
            with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
                f.write(f"{mins}:{secs:02d}")
        except OSError:
            pass          # a file locked by OBS for a moment is not worth crashing over
        time.sleep(0.25)


threading.Thread(target=write_timer_file, daemon=True).start()

ws = websocket.create_connection(URL)
print(f"connected — timer running, writing to {OUTPUT_FILE}\n")

while True:
    frame = json.loads(ws.recv())
    if frame["type"] != "events":
        continue

    for event in frame["events"]:
        who = event["user"]["nick"] or event["user"]["uid"]

        if event["kind"] == "gift":
            gift = event["gift"]
            # "value" is already diamonds x count, so a combo of 10 Roses counts as 10.
            add_time(gift["value"] * SECONDS_PER_COIN,
                     f"{who} sent {event['count']}x {gift['name']}")

        elif event["kind"] == "follow":
            add_time(SECONDS_PER_FOLLOW, f"{who} followed")
