"""
EIP-712 signing for Aster's V3 API wallet, without eth-account (which can't install on Python 3.8).
Uses only 'ecdsa' (pure Python) and 'pycryptodome' (Keccak), both with ready-made wheels.
Produces exactly the same signatures as eth-account (deterministic RFC 6979, low-s, v = 27/28).
"""
import hashlib

from Crypto.Hash import keccak as _keccak
from ecdsa import SECP256k1
from ecdsa.rfc6979 import generate_k

G = SECP256k1.generator
N = SECP256k1.order


def keccak(b: bytes) -> bytes:
    h = _keccak.new(digest_bits=256)
    h.update(b)
    return h.digest()


def _priv_int(private_key: str) -> int:
    k = private_key.strip().lower()
    if k.startswith("0x"):
        k = k[2:]
    if len(k) != 64 or any(c not in "0123456789abcdef" for c in k):
        raise ValueError("The API wallet private key must be 64 hex characters (optionally starting with 0x)")
    d = int(k, 16)
    if not 0 < d < N:
        raise ValueError("Invalid private key")
    return d


def checksum(addr_hex: str) -> str:
    a = addr_hex.lower().replace("0x", "")
    h = keccak(a.encode()).hex()
    return "0x" + "".join(c.upper() if c.isalpha() and int(h[i], 16) >= 8 else c for i, c in enumerate(a))


def is_address(a: str) -> bool:
    a = (a or "").strip()
    return len(a) == 42 and a[:2].lower() == "0x" and all(c in "0123456789abcdefABCDEF" for c in a[2:])


def address_of(private_key: str) -> str:
    P = G * _priv_int(private_key)
    pub = P.x().to_bytes(32, "big") + P.y().to_bytes(32, "big")
    return checksum(keccak(pub)[-20:].hex())


def _u256(n: int) -> bytes:
    return n.to_bytes(32, "big")


def typed_message_digest(msg: str, chain_id: int, name="AsterSignTransaction", version="1",
                         verifying_contract="0x0000000000000000000000000000000000000000") -> bytes:
    domain_type = keccak(b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
    domain = keccak(domain_type + keccak(name.encode()) + keccak(version.encode()) + _u256(chain_id)
                    + bytes(12) + bytes.fromhex(verifying_contract[2:]))
    msg_type = keccak(b"Message(string msg)")
    struct = keccak(msg_type + keccak(msg.encode("utf-8")))
    return keccak(b"\x19\x01" + domain + struct)


def sign_digest(digest: bytes, private_key: str) -> str:
    d = _priv_int(private_key)
    z = int.from_bytes(digest, "big")
    k = generate_k(N, d, hashlib.sha256, digest)
    R = G * k
    r = R.x() % N
    s = pow(k, -1, N) * (z + r * d) % N
    recid = (R.y() & 1) | (2 if R.x() >= N else 0)
    if s > N // 2:                     # canonical low-s, like Ethereum
        s = N - s
        recid ^= 1
    return "0x" + (_u256(r) + _u256(s) + bytes([27 + recid])).hex()


def sign_typed_message(msg: str, chain_id: int, private_key: str) -> str:
    return sign_digest(typed_message_digest(msg, chain_id), private_key)
