import sqlite3
import json
import os

db_path = r"J:\Softwareprojekte\Polytrader\DBBackup\polytrader.db"
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()

# Accounts
cursor.execute("SELECT * FROM polymarket_accounts")
accounts_rows = cursor.fetchall()
accounts_dict = {}
for r in accounts_rows:
    acc = dict(r)
    # Map to C# AccountState
    acc_obj = {
        "AccountId": acc["id"],
        "Name": acc["name"],
        "WalletAddress": acc["wallet_address"],
        "ApiKey": acc["api_key"] or "",
        "ApiSecret": acc["api_secret"] or "",
        "ApiPassphrase": acc["api_passphrase"] or "",
        "PrivateKey": acc["private_key"] or "",
        "IsDemo": bool(acc["is_demo"]),
        "IsActive": bool(acc["is_active"]),
        "CloseOnlyMode": bool(acc["close_only_mode"]),
        "PayoutAddress": acc["payout_address"] or "",
        "PayoutLimitUsd": float(acc["payout_limit_usd"] or 0),
        "PerMarketLimit": float(acc["per_market_limit"] or acc.get("max_trade_percent", 5.0)),
        "MaxPriceDifference": float(acc["max_price_difference"] or 2.0),
        "MaxBuyPrice": float(acc["max_buy_price"] or 0.98),
        "ProfitTarget": float(acc["profit_target"] or 50.0),
        "LimitUnder6h": float(acc["limit_under_6h"] or 20.0),
        "LimitUnder24h": float(acc["limit_under_24h"] or 20.0),
        "LimitUnder72h": float(acc["limit_under_72h"] or 20.0),
        "LimitOver72h": float(acc["limit_over_72h"] or 40.0),
        "TotalBalance": 0.0,
        "AvailableBalance": 0.0,
        "OpenPositions": {}
    }
    accounts_dict[str(acc["id"])] = acc_obj

# Traders
cursor.execute("SELECT * FROM tracked_traders")
traders_rows = cursor.fetchall()

# Links
cursor.execute("SELECT * FROM trader_account_links")
links_rows = cursor.fetchall()
links_map = {}
for r in links_rows:
    t_id = r["trader_id"]
    a_id = r["account_id"]
    if t_id not in links_map:
        links_map[t_id] = []
    links_map[t_id].append(a_id)

traders_dict = {}
for r in traders_rows:
    t = dict(r)
    t_id = t["id"]
    trader_obj = {
        "Id": t_id,
        "WalletAddress": t["wallet_address"],
        "Category": t["category"] or "",
        "DisplayName": t["display_name"] or "",
        "Description": t["description"] or "",
        "Reasoning": t["reasoning"] or "",
        "IsActive": bool(t["is_active"]),
        "IsHidden": bool(t["is_hidden"]),
        "TotalTrades": int(t["total_trades"] or 0),
        "WinningTrades": int(t["winning_trades"] or 0),
        "Winrate30t": float(t["winrate_30t"] or 0.0),
        "TotalPnl": float(t["total_pnl"] or 0.0),
        "AssignedAccountIds": links_map.get(t_id, [])
    }
    traders_dict[str(t_id)] = trader_obj

snapshot = {
    "GlobalTradingPaused": False,
    "LiveTradingMode": 0,
    "DemoTradingMode": 0,
    "Accounts": accounts_dict,
    "Traders": traders_dict,
    "TotalCopyTrades": 0,
    "GlobalPnl": 0.0
}

with open("snapshot.json", "w") as f:
    json.dump(snapshot, f, indent=4)

print("Export to snapshot.json complete! File size:", os.path.getsize("snapshot.json"))
