# litcoin/wallet.py
"""Wallet abstraction for Bankr smart wallets and EOA private keys."""

import requests


class BankrWallet:
    """Bankr smart contract wallet — signs via Bankr API."""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://bankr.bot/api"
        self._address = None

    @property
    def address(self) -> str:
        if not self._address:
            self._address = self._resolve_address()
        return self._address

    @property
    def wallet_type(self) -> str:
        return "bankr"

    def sign(self, message: str) -> str:
        resp = requests.post(
            f"{self.base_url}/agent/sign",
            headers=self._headers(),
            json={"signatureType": "personal_sign", "message": message},
            timeout=30,
        )
        resp.raise_for_status()
        return resp.json().get("signature")

    def submit_tx(self, to: str, data: str, value: str = "0") -> dict:
        resp = requests.post(
            f"{self.base_url}/agent/submit",
            headers=self._headers(),
            json={"transaction": {"to": to, "data": data, "value": value, "chainId": 8453}},
            timeout=60,
        )
        resp.raise_for_status()
        return resp.json()

    def _headers(self) -> dict:
        return {"Content-Type": "application/json", "X-API-Key": self.api_key}

    def _resolve_address(self) -> str:
        resp = requests.get(f"{self.base_url}/agent/me", headers=self._headers(), timeout=15)
        resp.raise_for_status()
        data = resp.json()
        for key in ("wallets", "addresses"):
            items = data.get(key, [])
            if isinstance(items, list):
                for w in items:
                    addr = w.get("address", w) if isinstance(w, dict) else w
                    if isinstance(addr, str) and addr.startswith("0x"):
                        return addr
        for key in ("address", "evmAddress", "wallet"):
            if key in data and isinstance(data[key], str) and data[key].startswith("0x"):
                return data[key]
        raise RuntimeError(f"Could not resolve Bankr wallet address: {data}")


class EOAWallet:
    """EOA wallet — signs locally with private key via eth-account."""

    def __init__(self, private_key: str):
        try:
            from eth_account import Account
            from eth_account.messages import encode_defunct
        except ImportError:
            raise ImportError("pip install eth-account  (required for EOA wallets)")
        self._account = Account.from_key(private_key)
        self._encode_defunct = encode_defunct

    @property
    def address(self) -> str:
        return self._account.address

    @property
    def wallet_type(self) -> str:
        return "eoa"

    def sign(self, message: str) -> str:
        from eth_account.messages import encode_defunct
        msg = encode_defunct(text=message)
        signed = self._account.sign_message(msg)
        return signed.signature.hex()
        
    def submit_tx(self, to: str, data: str, value: str = "0") -> dict:
        raise NotImplementedError(
            "EOA wallets submit transactions via the frontend dashboard at litcoiin.xyz/dashboard"
        )


def create_wallet(wallet_key: str):
    """Auto-detect wallet type from key format."""
    if wallet_key.startswith("bk_"):
        return BankrWallet(wallet_key)
    elif wallet_key.startswith("0x") and len(wallet_key) == 66:
        return EOAWallet(wallet_key)
    else:
        raise ValueError(
            "wallet_key must be a Bankr API key (bk_...) or an Ethereum private key (0x...)"
        )
