import argparse
import os
import sys

import eth_account
import requests
from dotenv import load_dotenv
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info

from panic_guard import expected_confirmation, validate_panic_confirmation


def main(argv=None):
    parser = argparse.ArgumentParser(description="PANIC CLOSE: alle offenen Hyperliquid Positionen schließen")
    parser.add_argument("--confirm", required=False, help="Exakte Bestätigung: CLOSE ALL <wallet-last4>")
    args = parser.parse_args(argv)

    load_dotenv()
    secret_key = os.getenv("HL_API_PRIVATE_KEY")
    wallet_address = os.getenv("HL_WALLET_ADDRESS")

    if not secret_key or not wallet_address:
        print("❌ FATAL: API Key oder Wallet Address fehlen!")
        return 2

    expected = expected_confirmation(wallet_address)
    if not validate_panic_confirmation(args.confirm, wallet_address):
        print("❌ PANIC CLOSE blockiert: explizite Bestätigung fehlt oder ist falsch.")
        print(f"   Erwartet: --confirm \"{expected}\"")
        return 3

    print("🚨 PANIC CLOSE INITIIERT: Verbinde mit Hyperliquid...")
    account = eth_account.Account.from_key(secret_key)
    exchange = Exchange(account, "https://api.hyperliquid.xyz")
    info = Info("https://api.hyperliquid.xyz", skip_ws=True)

    try:
        sz_decimals = {}
        r = requests.post("https://api.hyperliquid.xyz/info", headers={"Content-Type": "application/json"}, json={"type": "metaAndAssetCtxs"})
        if r.status_code == 200:
            for i, coin_info in enumerate(r.json()[0]["universe"]):
                sz_decimals[coin_info["name"]] = coin_info["szDecimals"]

        u_state = info.user_state(wallet_address)
        positions = u_state.get("assetPositions", [])
        closed_count = 0
        for p in positions:
            szi = float(p["position"]["szi"])
            if szi != 0:
                coin = p["position"]["coin"]
                is_buy = szi < 0
                exact_sz = abs(szi)
                decimals = sz_decimals.get(coin, 0)
                rounded_sz = round(exact_sz, decimals) if decimals > 0 else int(exact_sz)
                print(f"⚠️ Schließe {coin} (Size: {rounded_sz}) per Market-Order...")
                res = exchange.market_open(coin, is_buy, rounded_sz, slippage=0.05)
                if res and res.get("status") == "ok":
                    print(f"✅ {coin} erfolgreich geschlossen.")
                    closed_count += 1
                else:
                    print(f"❌ Fehler bei {coin}: {res}")

        print(f"🏁 PANIC CLOSE BEENDET. {closed_count} Positionen geschlossen.")
        return 0
    except Exception as e:
        print(f"🔥 FATALER FEHLER: {e}")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
