import os
from dotenv import load_dotenv
from hyperliquid.info import Info
from hyperliquid.utils import constants

from config import BotConfig, RuntimePaths

load_dotenv()
CONFIG = BotConfig.from_file()
PATHS = RuntimePaths.from_config(CONFIG)
PATHS.ensure_dirs()
WALLET_ADDRESS = os.getenv("HL_MAIN_ADDRESS")

if not WALLET_ADDRESS:
    WALLET_ADDRESS = os.getenv("HL_API_WALLET_ADDRESS")

def check_health():
    if not WALLET_ADDRESS:
        print("❌ Fehler: Keine Adresse in der .env gefunden.")
        return

    info = Info(constants.MAINNET_API_URL, skip_ws=True)

    try:
        # 1. Perp-Daten abrufen (für die offenen Trades und den PnL)
        user_state = info.user_state(WALLET_ADDRESS)
        positions = user_state.get("assetPositions", [])
        active_trades = [p for p in positions if float(p["position"]["szi"]) != 0]
        trade_count = len(active_trades)
        
        unrealized_pnl = sum(float(p["position"].get("unrealizedPnl", 0)) for p in active_trades)
        
        # 2. Unified/Spot-Daten abrufen (Hier liegt im Portfolio Margin das echte Geld!)
        spot_state = info.spot_user_state(WALLET_ADDRESS)
        spot_balances = spot_state.get("balances", [])
        
        usdc_total = 0.0
        usdc_hold = 0.0
        
        for b in spot_balances:
            if b["coin"] == "USDC":
                usdc_total = float(b["total"])
                usdc_hold = float(b["hold"]) # Das ist die gebundene Margin
                break
                
        free_usdc = usdc_total - usdc_hold
        account_value = usdc_total + unrealized_pnl
        margin_usage_pct = (usdc_hold / account_value * 100) if account_value > 0 else 0

        # Bericht formatieren
        report = (
            f"📊 Portfolio-Status (Unified Margin):\n"
            f"Nettovermögen (Equity): ${account_value:.2f}\n"
            f"Freies USDC: ${free_usdc:.2f}\n"
            f"Gebundene Margin: ${usdc_hold:.2f}\n"
            f"Offener PnL: ${unrealized_pnl:.2f}\n"
            f"Risiko-Auslastung: {margin_usage_pct:.1f}%\n"
            f"Offene Trades: {trade_count}"
        )
        
        print(report)
        
        with open(PATHS.account_health, "w", encoding="utf-8") as f:
            f.write(report)

    except Exception as e:
        print(f"❌ Fehler beim Abrufen der Börsen-Daten: {e}")

if __name__ == "__main__":
    check_health()
