#!/usr/bin/env python3
"""
Waybar module for controlling Studio Sound power outlet
Toggles power on click and shows current status
"""

import json
import requests
import sys
import os

STATUS_URL = 'http://192.168.1.75/cm?cmnd=status'
TOGGLE_URL = 'http://192.168.1.75/ay?o=1'
CACHE_FILE = '/tmp/studio_sound_status.json'
TIMEOUT = 2  # seconds

def get_status():
    """Fetch the current power status from the device"""
    try:
        response = requests.get(STATUS_URL, timeout=TIMEOUT)
        response.raise_for_status()
        data = response.json()
        return data.get('Status', {}).get('Power', 0) == 1
    except:
        # Return cached status if available
        if os.path.exists(CACHE_FILE):
            try:
                with open(CACHE_FILE, 'r') as f:
                    cached = json.load(f)
                    return cached.get('power', False)
            except:
                pass
        return False

def toggle_power():
    """Toggle the power state"""
    try:
        requests.get(TOGGLE_URL, timeout=TIMEOUT)
        # Give device time to process
        import time
        time.sleep(0.5)
        return get_status()
    except:
        return False

def save_cache(power_state):
    """Save current state to cache file"""
    try:
        with open(CACHE_FILE, 'w') as f:
            json.dump({'power': power_state}, f)
    except:
        pass

def main():
    # Check if this is a click event
    if len(sys.argv) > 1 and sys.argv[1] == 'toggle':
        power_state = toggle_power()
    else:
        power_state = get_status()
    
    # Save to cache
    save_cache(power_state)
    
    # Output JSON for waybar
    output = {
        "text": "Studio " if power_state else "Studio ",
        "tooltip": f"Studio Sound: {'ON' if power_state else 'OFF'}",
        "class": "studio-sound-on" if power_state else "studio-sound-off",
        "alt": "on" if power_state else "off"
    }
    
    print(json.dumps(output))
    sys.stdout.flush()

if __name__ == "__main__":
    main()
