#!/usr/bin/env python3
import json, socket, sys, time, urllib.request, urllib.error
from pathlib import Path

CFG = Path(__file__).with_name('polux-camera-bridge.json')

def tcp_ok(host, port, timeout=2.0):
    try:
        with socket.create_connection((host, int(port)), timeout=timeout):
            return True
    except OSError:
        return False

def post(url, payload):
    data=json.dumps(payload).encode('utf-8')
    req=urllib.request.Request(url,data=data,headers={'Content-Type':'application/json','User-Agent':'POLUX-Camera-Bridge/3.6.8'},method='POST')
    with urllib.request.urlopen(req,timeout=8) as r:
        return r.status, r.read().decode('utf-8','replace')

def run_once(cfg):
    ip=cfg['ip_address']; onp=int(cfg.get('onvif_port',80)); rtp=int(cfg.get('rtsp_port',554))
    on_ok=tcp_ok(ip,onp); rt_ok=tcp_ok(ip,rtp)
    payload={
      'apartment_id':cfg['apartment_id'],'token':cfg['token'],'identifier':cfg['identifier'],
      'ip_address':ip,'onvif_port':onp,'rtsp_port':rtp,'onvif_ok':on_ok,'rtsp_ok':rt_ok
    }
    try:
        status, body=post(cfg['endpoint'],payload)
        print(time.strftime('%Y-%m-%d %H:%M:%S'), 'HTTP', status, body)
    except Exception as e:
        print(time.strftime('%Y-%m-%d %H:%M:%S'), 'ERROR', repr(e))
    return on_ok or rt_ok

def main():
    if not CFG.exists():
        sample={
          'endpoint':'https://polux.redesctcm.com/api/camera-heartbeat-v368.php',
          'apartment_id':'serranias-605','token':'PEGUE_AQUI_LA_CLAVE_DEL_BRIDGE',
          'identifier':'C0:8A:60:1F:00:F9','ip_address':'192.168.10.18',
          'onvif_port':80,'rtsp_port':554,'interval_seconds':60
        }
        CFG.write_text(json.dumps(sample,indent=2),encoding='utf-8')
        print('Creado',CFG,'Edite token/puertos si corresponde y ejecute de nuevo.')
        return 2
    cfg=json.loads(CFG.read_text(encoding='utf-8'))
    once='--once' in sys.argv
    while True:
        run_once(cfg)
        if once: break
        time.sleep(max(15,int(cfg.get('interval_seconds',60))))
    return 0
if __name__=='__main__': raise SystemExit(main())
