import os
import base64
import datetime
import requests
from dotenv import load_dotenv
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend

load_dotenv()

KEY_ID = os.getenv("KALSHI_API_KEY_ID")
KEY_PATH = os.getenv("KALSHI_PRIVATE_KEY_PATH")
BASE_URL = "https://api.elections.kalshi.com"

def load_private_key(file_path):
    with open(file_path, "rb") as f:
        return serialization.load_pem_private_key(
            f.read(), password=None, backend=default_backend()
        )

def sign_request(private_key, timestamp, method, path):
    message = (timestamp + method + path).encode("utf-8")
    signature = private_key.sign(
        message,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.DIGEST_LENGTH
        ),
        hashes.SHA256()
    )
    return base64.b64encode(signature).decode("utf-8")

def get_headers(method, path):
    timestamp = str(int(datetime.datetime.now().timestamp() * 1000))
    private_key = load_private_key(KEY_PATH)
    sig = sign_request(private_key, timestamp, method, path)
    return {
        "KALSHI-ACCESS-KEY": KEY_ID,
        "KALSHI-ACCESS-TIMESTAMP": timestamp,
        "KALSHI-ACCESS-SIGNATURE": sig,
        "Content-Type": "application/json"
    }

# Test connection by fetching balance
path = "/trade-api/v2/portfolio/balance"
headers = get_headers("GET", path)
response = requests.get(BASE_URL + path, headers=headers)

if response.status_code == 200:
    data = response.json()
    balance = data.get("balance", 0) / 100
    print(f"Connection successful!")
    print(f"Your balance: ${balance:.2f}")
else:
    print(f"Error {response.status_code}: {response.text}")