import argparse
import hashlib
import hmac
import json
import os
import time
import uuid
import requests

INTEGRATION_BASE_URL = os.getenv("INTEGRATION_BASE_URL", "http://localhost:8800")
AGX_HMAC_SECRET = os.getenv("AGX_HMAC_SECRET", "")


def sign(body: dict):
    if not AGX_HMAC_SECRET:
        return {}
    ts = str(int(time.time() * 1000))
    nonce = str(uuid.uuid4())
    body_json = json.dumps(body, separators=(",", ":"), sort_keys=True)
    payload = f"{ts}.{nonce}.{body_json}"
    sig = hmac.new(AGX_HMAC_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {
        "X-AGX-SIGNATURE": sig,
        "X-AGX-TIMESTAMP": ts,
        "X-AGX-NONCE": nonce,
        "Content-Type": "application/json"
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--trace", default="", help="Override trace id for replay call")
    args = parser.parse_args()

    body = {}
    headers = sign(body)
    headers["X-AGX-REPLAY"] = "1"
    if args.trace:
        headers["X-AGX-TRACE-ID"] = args.trace

    resp = requests.post(f"{INTEGRATION_BASE_URL}/dlq/replay", data=json.dumps(body), headers=headers, timeout=30)
    print(resp.status_code, resp.text)


if __name__ == "__main__":
    main()
