import os
import sys
import time
import threading
import requests
import webview


class RCTVApp:
    def __init__(self, token):
        self.token = token
        self.api_url = f"https://rctv.recurse.com/get_all_apps_for_tauri?tv_login_token={token}"
        self.apps = []
        self.current_index = 0
        self.window = None
        self.running = True

    def fetch_apps(self):
        """Fetch apps from the API."""
        try:
            response = requests.get(self.api_url)
            response.raise_for_status()
            data = response.json()
            self.apps = data['apps']
            print(f"Loaded {len(self.apps)} apps")
            return True
        except Exception as e:
            print(f"Error fetching apps: {e}", file=sys.stderr)
            return False

    def rotate_pages(self):
        """Rotate through pages based on timing from API."""
        while self.running:
            if not self.apps:
                if not self.fetch_apps():
                    time.sleep(10)
                    continue
                self.current_index = 0

            if self.current_index >= len(self.apps):
                # End of loop, reload apps
                print("Reloading apps...")
                self.current_index = 0
                if not self.fetch_apps():
                    time.sleep(10)
                    continue

            app = self.apps[self.current_index]
            url = app.get('url', '')
            duration = app.get('on_screen_duration_seconds', 10)

            print(f"Showing: {url} for {duration}s")

            if self.window:
                self.window.load_url(url)

            time.sleep(duration)
            self.current_index += 1

    def start(self):
        """Start the application."""
        # Fetch initial apps
        if not self.fetch_apps():
            print("Failed to fetch initial apps. Exiting.", file=sys.stderr)
            sys.exit(1)

        # Start rotation in a separate thread
        rotation_thread = threading.Thread(target=self.rotate_pages, daemon=True)
        rotation_thread.start()

        # Create and show window
        self.window = webview.create_window(
            'RCTV',
            self.apps[0].get('url', 'about:blank') if self.apps else 'about:blank',
            fullscreen=True
        )
        webview.start()

        # Clean up
        self.running = False


def main():
    token = os.environ.get('RCTV_TOKEN')

    if not token:
        print("Error: RCTV_TOKEN environment variable is required", file=sys.stderr)
        sys.exit(1)

    app = RCTVApp(token)
    app.start()


if __name__ == "__main__":
    main()
