# lambda_function.py
import json
import time
import ssl
import urllib.request

# -----------------------------
# CONFIG: put your values here
# -----------------------------
API_URL = "https://app.kpifire.com/api/ext/metric/batchUpdate"

# Required headers
API_KEY = "e11b4590-6b24-48aa-bc98-8b4ec8c"
SECRET_API_KEY = "$2a$08$8qi4nQZYpNgYo4PqdDCHP.5T3KmE7XNAUA6kOL"

# Example payload (ARRAY of datapoints expected by KPI Fire)
PAYLOAD = [
    {
        "id": 56833,              # KPI Fire metric ID
        "date": "2025-01-02",     # YYYY-MM-DD
        "actual": 10.2,
        "target": 12.0,
        "beginGreen": 0,
        "beginYellow": 0,
        "beginRed": 0,
        "mean": 0,
        "endGreen": 0,
        "endYellow": 0,
        "endRed": 0,
        "reasonCode": "",
        "note": "Posted from Lambda test"
    }
]

# HTTP behavior
TIMEOUT_SECONDS = 20
RETRY_ON_NON_2XX = True
RETRY_SLEEP_SECS = 1.5


# ---------- Helper: POST JSON ----------
def http_post_json(url: str, body_obj: object, headers: dict, timeout: float) -> tuple[int, str]:
    data = json.dumps(body_obj).encode("utf-8")
    req = urllib.request.Request(url, data=data, headers=headers, method="POST")
    ctx = ssl.create_default_context()
    with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
        payload = resp.read().decode("utf-8", "ignore")
        return resp.status, payload


# -------------- Lambda handler --------------
def lambda_handler(event, context):
    # Always use api-key + secret-api-key headers
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "api-key": API_KEY,
        "secret-api-key": SECRET_API_KEY,
    }

    # Post with one retry on non-2xx
    attempts = 2 if RETRY_ON_NON_2XX else 1
    status, body = None, None
    for attempt in range(1, attempts + 1):
        try:
            status, body = http_post_json(API_URL, PAYLOAD, headers, TIMEOUT_SECONDS)
            if 200 <= status < 300:
                break
        except Exception as e:
            status, body = 0, f"{type(e).__name__}: {e}"
        if attempt < attempts:
            time.sleep(RETRY_SLEEP_SECS)

    result = {
        "request": {
            "url": API_URL,
            "headers_used": ["api-key", "secret-api-key", "Content-Type", "Accept"],
            "items": len(PAYLOAD),
        },
        "response": {
            "status": status,
            "body": (body[:2000] if isinstance(body, str) else str(body))  # truncate
        }
    }

    if not (200 <= (status or 0) < 300):
        raise RuntimeError(f"POST failed: {json.dumps(result['response'])}")

    return result
    
