#!/usr/bin/env python3
"""
tuya_bridge.py
Bridge antara PHP (tuya_api.php) dan tinytuya library.
Dipanggil oleh PHP via shell_exec.

Usage:
    python tuya_bridge.py <device_id> <ip> <local_key> <version> <action>

action:
    status  -> cek status ON/OFF dan power (watt)
    on      -> nyalakan plug
    off     -> matikan plug

Output: JSON satu baris ke stdout
    {"ok": true, "is_on": true, "power": 12.5}
    {"ok": false, "msg": "...pesan error..."}
"""

import sys
import json
import time

def main():
    # ── Ambil argumen ──────────────────────────────────────
    if len(sys.argv) < 6:
        print(json.dumps({
            "ok": False,
            "msg": "Usage: tuya_bridge.py <device_id> <ip> <local_key> <version> <action>"
        }))
        sys.exit(1)

    device_id = sys.argv[1]
    ip        = sys.argv[2]
    local_key = sys.argv[3]
    version   = sys.argv[4]
    action    = sys.argv[5].lower()

    # ── Import tinytuya ────────────────────────────────────
    try:
        import tinytuya
    except ImportError:
        print(json.dumps({
            "ok": False,
            "msg": "tinytuya tidak terinstall. Jalankan: pip install tinytuya"
        }))
        sys.exit(1)

    # ── Koneksi ke perangkat ───────────────────────────────
    try:
        device = tinytuya.OutletDevice(device_id, ip, local_key)
        device.set_version(float(version))
        device.set_socketTimeout(4)    # timeout 4 detik — sama dengan bot.py
        device.set_socketRetryLimit(2) # 2x retry
    except Exception as e:
        print(json.dumps({"ok": False, "msg": f"Gagal inisialisasi device: {str(e)}"}))
        sys.exit(1)

    # ── Eksekusi action ────────────────────────────────────
    try:
        if action == 'status':
            status = device.status()
            if not status or 'dps' not in status:
                print(json.dumps({"ok": False, "msg": "Tidak ada respons dari device"}))
                sys.exit(1)

            dps    = status['dps']
            # DPS key '1' adalah switch ON/OFF (sesuai tinytuya OutletDevice)
            is_on  = bool(dps.get('1', dps.get('1,', False)))
            # DPS key '19' adalah power (dalam 0.1W — sama persis dengan bot.py)
            power  = dps.get('19', 0) / 10.0

            print(json.dumps({
                "ok":    True,
                "is_on": is_on,
                "power": round(power, 1),
                "raw_dps": {str(k): v for k, v in dps.items()}
            }))

        elif action == 'on':
            device.turn_on()
            time.sleep(0.5)   # beri jeda sebelum baca status balik
            status = device.status()
            dps    = status.get('dps', {}) if status else {}
            is_on  = bool(dps.get('1', True))  # asumsikan ON jika tidak bisa baca
            power  = dps.get('19', 0) / 10.0

            print(json.dumps({
                "ok":    True,
                "is_on": is_on,
                "power": round(power, 1)
            }))

        elif action == 'off':
            device.turn_off()
            time.sleep(0.5)
            status = device.status()
            dps    = status.get('dps', {}) if status else {}
            is_on  = bool(dps.get('1', False))
            power  = dps.get('19', 0) / 10.0

            print(json.dumps({
                "ok":    True,
                "is_on": is_on,
                "power": round(power, 1)
            }))

        else:
            print(json.dumps({"ok": False, "msg": f"Action tidak dikenal: {action}"}))
            sys.exit(1)

    except Exception as e:
        print(json.dumps({"ok": False, "msg": f"Error komunikasi Tuya: {str(e)}"}))
        sys.exit(1)


if __name__ == '__main__':
    main()
