import base64, json, os, sys, urllib.parse, urllib.request, urllib.error
from datetime import datetime, timezone


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


def _headers(cfg):
    h = {"Accept": "application/json", "Content-Type": "application/json"}
    if str(cfg.get("auth_type") or "basic").lower() == "oauth":
        data = urllib.parse.urlencode({
            "grant_type": "password",
            "client_id": cfg.get("client_id", ""),
            "client_secret": cfg.get("client_secret", ""),
            "username": cfg.get("username", ""),
            "password": cfg.get("password", ""),
        }).encode("utf-8")
        req = urllib.request.Request(
            cfg.get("url", "").rstrip("/") + "/oauth_token.do", data=data,
            headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}, method="POST")
        with urllib.request.urlopen(req, timeout=60) as r:
            tok = json.loads(r.read())
        if not tok.get("access_token"):
            raise Exception("OAuth token request failed: " + json.dumps(tok))
        h["Authorization"] = "Bearer " + tok["access_token"]
    else:
        cred = (cfg.get("username", "") + ":" + cfg.get("password", "")).encode("utf-8")
        h["Authorization"] = "Basic " + base64.b64encode(cred).decode("ascii")
    return h


def request(method, path, params=None, body=None, root="/api/now", versioned=True):
    cfg = _cfg()
    v = str(cfg.get("api_version") or "").strip().strip("/")
    url = cfg.get("url", "").rstrip("/") + root + ("/" + v if v and versioned else "") + path
    q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
    if q:
        url += "?" + urllib.parse.urlencode(q)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(url, data=data, headers=_headers(cfg), method=method)
    with urllib.request.urlopen(req, timeout=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def to_snow_time(v):
    """Normalize ISO8601 / epoch (s or ms) / native format to 'YYYY-MM-DD HH:MM:SS' UTC."""
    s = str(v or "").strip()
    if not s:
        return None
    if s.isdigit():
        ts = int(s)
        if ts > 10**12:
            ts //= 1000
        return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
    if len(s) == 19 and s[4] == "-" and s[10] == " ":
        return s
    try:
        dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
        if dt.tzinfo is not None:
            dt = dt.astimezone(timezone.utc)
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return s


def main():
    cfg = _cfg()
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    table = str(inputs.get("ticket_type") or cfg.get("ticket_type") or "incident")
    ts_field = str(cfg.get("timestamp_field") or "opened_at")
    limit = int(inputs.get("limit") or 100)

    parts = []
    if inputs.get("query"):
        parts.append(str(inputs["query"]))
    watermark = to_snow_time(inputs.get("created_after"))
    if watermark:
        parts.append(ts_field + ">" + watermark)
    parts.append("ORDERBY" + ts_field)

    print(json.dumps(request("GET", "/table/" + urllib.parse.quote(table), params={
        "sysparm_query": "^".join(parts),
        "sysparm_limit": limit,
    })))


try:
    main()
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)
