import json
import os
import sys

import eth_account
from hyperliquid.info import Info

from .secrets import resolve_private_key_from_env


def get_address(testnet: bool = False):
    print("Testnet" if testnet else "Mainnet")
    # If address is explicitly set, use it
    address = os.getenv("HYPERLIQUID_WALLET_ADDRESS")
    if address:
        return address
    # Otherwise derive address from private key
    try:
        private_key = resolve_private_key_from_env()
    except Exception as e:  # noqa: BLE001
        print(json.dumps({"error": f"Encrypted private key env is not set: {str(e)}"}))
        sys.exit(1)
    if not private_key.startswith("0x"):
        private_key = "0x" + private_key

    account = eth_account.Account.from_key(private_key)
    return account.address


def get_info():
    return Info(skip_ws=True, perp_dexs=["", "xyz"])


def query_info(args):
    info = get_info()
    result = []
    if args.command == "query":
        qc = str(getattr(args, "query_cmd", "") or "")

        if qc in {"user-state", "open-orders", "fills"}:
            addr = str(getattr(args, "address", "") or "").strip()
            query_address = addr if addr else get_address(args.testnet)

            if qc == "user-state":
                perps = info.user_state(query_address)
                spot = info.spot_user_state(query_address)
                perps_xyz = info.user_state(query_address, dex="xyz")
                result = {"crpto-perps": perps} | {"spot": spot} | {"HIP3-xyz": perps_xyz}
            elif qc == "open-orders":
                result = info.open_orders(query_address)
            elif qc == "fills":
                result = info.user_fills(query_address)
            return result

        if qc == "meta":
            crypto = info.meta()
            xyz = info.meta("xyz")
            result = crypto.get("universe") + xyz.get("universe")
            return result

        if qc == "mids":
            crypto = info.all_mids()
            xyz = info.all_mids("xyz")
            result = crypto | xyz
            result = {k: v for k, v in result.items() if not k.startswith("@")}
            return result

        if qc == "kline":
            return info.candles_snapshot(
                name=args.coin,
                interval=args.period,
                startTime=args.start,
                endTime=args.end,
            )

        raise SystemExit(f"unknown query command: {qc}")
    return result

