#!/usr/bin/env python3
import json
import os
import socket
import sys
import time
import urllib.request

PORTAL_URL = os.environ.get("WOL_PORTAL_URL", "").rstrip("/")
TOKEN = os.environ.get("WOL_AGENT_TOKEN", "")
INTERVAL = int(os.environ.get("WOL_INTERVAL", "10"))
ENDPOINT = PORTAL_URL + "/wol_agent.php"

if not PORTAL_URL or not TOKEN:
    sys.exit("Define WOL_PORTAL_URL e WOL_AGENT_TOKEN.")


def post(payload):
    data = json.dumps(payload).encode("utf-8")
    request = urllib.request.Request(
        ENDPOINT,
        data=data,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read().decode("utf-8"))


def send_wol(mac, broadcast, port):
    hex_mac = "".join(ch for ch in mac if ch in "0123456789abcdefABCDEF")
    if len(hex_mac) != 12:
        raise ValueError("MAC inválido")
    packet = b"\xff" * 6 + bytes.fromhex(hex_mac) * 16
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(packet, (broadcast or "255.255.255.255", int(port or 9)))
    sock.close()


def main():
    print(f"Agente WoL ligado a {ENDPOINT}", flush=True)
    while True:
        try:
            result = post({"action": "poll", "token": TOKEN})
            jobs = (result.get("data") or {}).get("jobs") or []
            for job in jobs:
                success = False
                message = ""
                try:
                    send_wol(job.get("mac", ""), job.get("broadcast"), job.get("port"))
                    success = True
                    message = "Pacote enviado"
                except Exception as exc:
                    message = str(exc)
                try:
                    post({
                        "action": "ack",
                        "token": TOKEN,
                        "job_id": job.get("id"),
                        "success": success,
                        "message": message,
                    })
                except Exception as exc:
                    print("Erro ao confirmar:", exc, flush=True)
                print(f"Pedido {job.get('id')}: {message}", flush=True)
        except Exception as exc:
            print(time.strftime("%H:%M:%S"), "Erro:", exc, flush=True)
        time.sleep(INTERVAL)


if __name__ == "__main__":
    main()
