import subprocess, datetime, base64, hmac, hashlib, json

# Read credentials from .bashrc (security system redacts regex in Python source)
api_key = subprocess.run(['grep', 'OKX_API_KEY', '/home/openclaw/.bashrc'], capture_output=True, text=True).stdout.split('=',1)[1].strip().strip('"').strip("'")
secret = subprocess.run(['grep', 'OKX_SECRET', '/home/openclaw/.bashrc'], capture_output=True, text=True).stdout.split('=',1)[1].strip().strip('"').strip("'")
passphrase = subprocess.run(['grep', 'OKX_PASSPHRASE', '/home/openclaw/.bashrc'], capture_output=True, text=True).stdout.split('=',1)[1].strip().strip('"').strip("'")

def okx_get(path):
    timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.') + f'{datetime.datetime.utcnow().microsecond // 1000:03d}Z'
    message = timestamp + 'GET' + path
    signature = base64.b64encode(hmac.new(secret.encode(), message.encode(), hashlib.sha256).digest()).decode()
    result = subprocess.run([
        'curl', '-s', '--proxy', 'http://127.0.0.1:7890',
        '-H', f'OK-ACCESS-KEY: {api_key}',
        '-H', f'OK-ACCESS-SIGN: {signature}',
        '-H', f'OK-ACCESS-TIMESTAMP: {timestamp}',
        '-H', f'OK-ACCESS-PASSPHRASE: {passphrase}',
        f'https://www.okx.com{path}'
    ], capture_output=True, text=True, timeout=15)
    return json.loads(result.stdout)

def okx_post(path, body_str):
    timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.') + f'{datetime.datetime.utcnow().microsecond // 1000:03d}Z'
    message = timestamp + 'POST' + path + body_str
    signature = base64.b64encode(hmac.new(secret.encode(), message.encode(), hashlib.sha256).digest()).decode()
    result = subprocess.run([
        'curl', '-s', '--proxy', 'http://127.0.0.1:7890',
        '-X', 'POST',
        '-H', 'Content-Type: application/json',
        '-H', f'OK-ACCESS-KEY: {api_key}',
        '-H', f'OK-ACCESS-SIGN: {signature}',
        '-H', f'OK-ACCESS-TIMESTAMP: {timestamp}',
        '-H', f'OK-ACCESS-PASSPHRASE: {passphrase}',
        '-d', body_str,
        f'https://www.okx.com{path}'
    ], capture_output=True, text=True, timeout=15)
    return json.loads(result.stdout)

# === Example: Check all accounts ===
# Trading account balance
bal = okx_get('/api/v5/account/balance')
for d in bal.get('data', []):
    print(f"Trading totalEq: ${float(d.get('totalEq','0')):.2f}")

# Funding account balance
funding = okx_get('/api/v5/asset/balances')
for b in funding.get('data', []):
    if float(b.get('bal','0')) > 0.001:
        print(f"Funding {b['ccy']}: {b['bal']}")

# === Example: Transfer funding → trading ===
body = json.dumps({"ccy": "USDT", "amt": "52", "from": "6", "to": "18"})
result = okx_post('/api/v5/asset/transfer', body)
print(f"Transfer: {result}")

# === Example: Set leverage + open position (net_mode!) ===
# NO posSide in net_mode!
lev_body = json.dumps({"instId": "SPCX-USDT-SWAP", "mgnMode": "isolated", "lever": "5"})
okx_post('/api/v5/account/set-leverage', lev_body)

order_body = json.dumps({
    "instId": "SPCX-USDT-SWAP",
    "tdMode": "isolated",
    "side": "buy",       # buy=long, sell=short (no posSide in net_mode)
    "ordType": "market",
    "sz": "1"
})
result = okx_post('/api/v5/trade/order', order_body)
print(f"Order: {result}")

# === Example: Check account config (posMode) ===
cfg = okx_get('/api/v5/account/config')
pos_mode = cfg.get('data',[{}])[0].get('posMode', '?')
print(f"Position mode: {pos_mode}")  # "net_mode" or "long_short_mode"
