import os, sys, datetime, json, subprocess
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)

IOTA = os.environ.get("IOTA_CLI", "/home/edward/.cargo/bin/iota")

from get_account_id_from_character_id_i import get_account_id_from_character_id
from get_wallet_credentials_i import get_wallet_credentials
from update_tungsten_balance import update_tungsten_balance

TR1T_TYPE = "0xf4d403ce2cb2d0a0b05af6945167acd933644c6c835dff577ae14e52edbf5bfd::tungsten::TUNGSTEN"
DECIMALS = 9

def _run(cmd):
    return subprocess.run(cmd, capture_output=True, text=True)

def _parse_tr1t_from_balance_json(txt: str):
    try:
        j = json.loads(txt)
    except json.JSONDecodeError:
        return None
    # Shape: [ [ [ {tokenMeta}, [ {coin}... ] ], [ {tokenMeta}, [ {coin}... ] ] ], false ]
    if not isinstance(j, list) or not j or not isinstance(j[0], list):
        return None
    total = 0
    for token_entry in j[0]:
        if not isinstance(token_entry, list) or len(token_entry) != 2:
            continue
        _meta, coins = token_entry
        if not isinstance(coins, list):
            continue
        for c in coins:
            if isinstance(c, dict) and TR1T_TYPE in str(c.get("coinType", "")):
                try:
                    total += int(c.get("balance", "0"))
                except Exception:
                    pass
    return total / (10 ** DECIMALS)

def _parse_tr1t_from_table(txt: str):
    # Look for a line that starts with "Tungsten" and capture the raw balance column.
    for line in txt.splitlines():
        parts = line.strip().split()
        if parts[:1] == ["Tungsten"] and len(parts) >= 3:
            raw = parts[1]  # balance (raw)
            try:
                return int(raw) / (10 ** DECIMALS)
            except Exception:
                return None
    return None

def get_wallet_balance(CharacterId: str, TESTING: bool = False) -> str:
    TESTING = True
    #print(f"\n{datetime.datetime.now()}", file=sys.stderr)

    if len(CharacterId) > 3:
        user_id = get_account_id_from_character_id(CharacterId)
    else:
        user_id = CharacterId
    address, _ = get_wallet_credentials(user_id, TESTING)
    alias = f"u{user_id}"

    # Prefer JSON against the alias (works on 1.7 CLI)
    b = _run([IOTA, "client", "balance", "--json", alias])
    #print(">>>",b.stdout,"<<<")
    if b.returncode == 0:
        v = _parse_tr1t_from_balance_json(b.stdout)
        if v is not None:
            #print(f"balance(TR1T): {v}", file=sys.stderr)
            update_tungsten_balance(user_id, int(v))
            return str(v)

    # Fallback: parse the human table
    t = _run([IOTA, "client", "balance", alias])
    if t.returncode == 0:
        v = _parse_tr1t_from_table(t.stdout)
        if v is not None:
            #print(f"balance(TR1T): {v}", file=sys.stderr)
            update_tungsten_balance(user_id, int(v))
            return str(v)

    # Final fallback
    print(f"balance fetch failed: json_rc={b.returncode}, table_rc={t.returncode}", file=sys.stderr)
    v = 0.0
    update_tungsten_balance(user_id, int(v))
    return str(v)

if __name__ == "__main__":
    character_id = sys.argv[1] if len(sys.argv) > 1 else '37'
    print(get_wallet_balance(character_id), end="", file=sys.__stdout__, flush=True)
