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

from config import BotConfig, RuntimePaths

load_dotenv()
CONFIG = BotConfig.from_file()
PATHS = RuntimePaths.from_config(CONFIG)
PATHS.ensure_dirs()
address = os.getenv("HL_MAIN_ADDRESS")
info = Info(constants.MAINNET_API_URL)

def log_profit():
    if not address:
        print("❌ Fehler: HL_MAIN_ADDRESS fehlt in der .env.")
        return
    print(f"Agent ist aktiv... Überwachung läuft für {address[:6]}")
    while True:
        try:
            # Daten abrufen
            vault_equities = info.user_vault_equities(address)
            vault_val = sum(float(v.get('equity', 0)) for v in vault_equities)
            
            # Zeitstempel erstellen
            now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_entry = f"[{now}] HLP-Wert: ${vault_val:.4f} USDC\n"
            
            # In Datei schreiben (Modus 'a' für anfügen)
            with open(PATHS.profit_history, "a", encoding="utf-8") as f:
                f.write(log_entry)
            
            print(f"Update geschrieben: {log_entry.strip()}")
            
            # 1 Stunde warten (3600 Sekunden)
            time.sleep(3600)
            
        except Exception as e:
            print(f"Fehler: {e}")
            time.sleep(60) # Bei Fehler kurz warten und neu versuchen

if __name__ == "__main__":
    log_profit()
