import hashlib
import hmac
import json
import os
import time

import requests


BASE_URL = os.getenv("VOXI_BASE_URL", "http://localhost:3000")
WEBHOOK_URL = os.getenv(
    "VOXI_WEBHOOK_URL",
    f"{BASE_URL}/api/v1/webhooks/incoming/replace-me",
)
WEBHOOK_SECRET = os.getenv("VOXI_WEBHOOK_SECRET", "replace-me")


def sign(raw_body: str, timestamp: str) -> str:
    payload = f"{timestamp}.{raw_body}".encode("utf-8")
    digest = hmac.new(
        WEBHOOK_SECRET.encode("utf-8"), payload, hashlib.sha256
    ).hexdigest()
    return f"sha256={digest}"


def main() -> None:
    body = {
        "username": "python-hook",
        "content": "Signed webhook mesaji Python orneginden gonderildi.",
    }
    raw_body = json.dumps(body, separators=(",", ":"))
    timestamp = str(int(time.time()))

    response = requests.post(
        WEBHOOK_URL,
        data=raw_body,
        headers={
            "Content-Type": "application/json",
            "x-voxi-timestamp": timestamp,
            "x-voxi-signature": sign(raw_body, timestamp),
        },
        timeout=10,
    )
    response.raise_for_status()
    print(response.json())


if __name__ == "__main__":
    main()