import json, os, sys, urllib.parse, urllib.request, urllib.error


def _cfg():
    return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))


def _inputs():
    return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))


def _base(cfg):
    return "https://api.telegram.org/bot" + str(cfg.get("bot_token", ""))


def call(method_name, cfg, body=None, params=None, http="POST"):
    url = _base(cfg) + "/" + method_name
    if params:
        clean = {k: v for k, v in params.items() if v not in (None, "")}
        if clean:
            url += "?" + urllib.parse.urlencode(clean)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Accept": "application/json"}
    if data is not None:
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, headers=headers, method=http)
    with urllib.request.urlopen(req, timeout=60) as r:
        resp = json.loads(r.read() or "{}")
    if not resp.get("ok"):
        raise Exception("Telegram error: " + json.dumps(resp))
    return resp


def _run(fn):
    try:
        print(json.dumps(fn(_cfg(), _inputs())))
    except urllib.error.HTTPError as e:
        print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
        sys.exit(1)
    except Exception as e:
        print(json.dumps({"error": str(e)}))
        sys.exit(1)


_chat = lambda cfg, inputs: (inputs.get("chat_id") or cfg.get("default_chat_id"))


def main(cfg, inputs):
    chat = _chat(cfg, inputs)
    if not chat:
        raise Exception("chat_id is required (set a default or pass one)")

    photo = inputs.get("photo")
    if not photo:
        raise Exception("photo is required")

    caption = inputs.get("caption")

    body = {"chat_id": chat, "photo": photo}
    if caption:
        body["caption"] = caption

    resp = call("sendPhoto", cfg, body=body)
    return resp


_run(main)
