import json, os, sys, base64, uuid, 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 (str(cfg.get("base_url") or "https://tria.ge")).rstrip("/")


def _headers(cfg, extra=None):
    h = {"Accept": "application/json", "Authorization": "Bearer " + str(cfg.get("api_token", ""))}
    if extra:
        h.update(extra)
    return h


def request(method, path, cfg, body=None, params=None):
    url = _base(cfg) + path
    if params:
        clean = {k: v for k, v in params.items() if v not in (None, "")}
        if clean:
            url += "?" + urllib.parse.urlencode(clean)
    data = None
    extra = {}
    if body is not None:
        data = json.dumps(body).encode("utf-8")
        extra["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, headers=_headers(cfg, extra), method=method)
    with urllib.request.urlopen(req, timeout=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def submit_file_multipart(cfg, file_name, file_bytes, json_meta):
    # Triage sample submission: multipart with a '_json' text part and a 'file' part.
    boundary = "----riposte" + uuid.uuid4().hex
    parts = []
    parts.append(("--" + boundary + "\r\n"
                  'Content-Disposition: form-data; name="_json"\r\n\r\n' + json.dumps(json_meta) + "\r\n").encode("utf-8"))
    parts.append(("--" + boundary + "\r\n"
                  'Content-Disposition: form-data; name="file"; filename="' + file_name + '"\r\n'
                  "Content-Type: application/octet-stream\r\n\r\n").encode("utf-8"))
    parts.append(file_bytes)
    parts.append(("\r\n--" + boundary + "--\r\n").encode("utf-8"))
    data = b"".join(parts)
    req = urllib.request.Request(_base(cfg) + "/api/v0/samples", data=data,
                                 headers=_headers(cfg, {"Content-Type": "multipart/form-data; boundary=" + boundary}),
                                 method="POST")
    with urllib.request.urlopen(req, timeout=180) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


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)


def main(cfg, inputs):
    sample_id = inputs.get("sample_id")
    if not sample_id:
        raise Exception("sample_id is required")
    q = lambda v: urllib.parse.quote(str(v), safe="")
    return request("GET", "/api/v0/samples/" + q(sample_id), cfg)


_run(main)
