import hmac
from hashlib import sha256
from fastecdsa.curve import P384
from fastecdsa.keys import gen_keypair

def p2i(P) -> int:
    return P.x * P.curve.p + P.y

def sign(sk, msg, curve=P384, hashfunc=sha256):
    key = hashfunc(str(sk).encode()).digest()
    try:
        k = int.from_bytes(key + hmac.new(key, msg, hashfunc).digest()) % curve.q
        print("int.from_bytes(bytes) worked!")
    except TypeError:
        print("int.from_bytes(bytes) failed")
        k = int.from_bytes(key + hmac.new(key, msg, hashfunc).digest(), 'big') % curve.q
        
    r = p2i(k * curve.G)
    try:
        e = int.from_bytes(hmac.new(r.to_bytes(1337), msg, hashfunc).digest()) % curve.q
        print("r.to_bytes(1337) worked!")
    except TypeError:
        print("r.to_bytes(1337) failed")
        e = int.from_bytes(hmac.new(r.to_bytes(1337, 'big'), msg, hashfunc).digest(), 'big') % curve.q
        
    s = (k + sk * e) % curve.q
    return r, s

sk, pk = gen_keypair(P384)
msg = b"test"
try:
    sign(sk, msg)
except Exception as e:
    print(f"Sign failed: {e}")
