#!/usr/bin/env python3
"""Balances + transaction amounts for a list of wallets across BTC, ETH and TRX.

Built for the "need a coder" task on microlancer (trace a dozen high-volume
wallets across three chains). Design decisions that matter for money numbers:

* amounts are emitted twice: exact minimal units (sats / wei / sun) and a decimal
  string. Never a float — a JSON float would silently drop the last digits of a
  balance, which is exactly the bug that makes these reports useless.
* one failing address does not kill the run: the error is recorded per row and
  the rest continues.
* no API keys. Public endpoints only, so you can run it tomorrow without signing
  up for anything: Blockstream for BTC, Blockscout for ETH, TronGrid for TRX.

    python multichain.py --wallets wallets.txt --out report.json --csv report.csv
    python multichain.py --demo            # a few well-known addresses

wallets.txt: one address per line, optional "chain:address", "# comment" ok.
"""
import argparse
import csv
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from decimal import Decimal

UA = {"User-Agent": "multichain-wallet-report/1.0"}
TIMEOUT = 25
RETRIES = 3

CHAINS = {
    "btc": {"unit": "sats", "decimals": 8, "label": "BTC"},
    "eth": {"unit": "wei", "decimals": 18, "label": "ETH"},
    "trx": {"unit": "sun", "decimals": 6, "label": "TRX"},
}


def http_json(url, tries=RETRIES):
    last = None
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers=UA)
            with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
                return json.loads(r.read().decode("utf-8", "replace"))
        except urllib.error.HTTPError as e:
            last = "HTTP %s %s" % (e.code, url.split("?")[0])
            if e.code in (400, 404):
                break
        except Exception as e:  # noqa: BLE001 - network shapes vary wildly
            last = "%s: %s" % (type(e).__name__, str(e)[:80])
        time.sleep(1.5 * (i + 1))
    raise RuntimeError(last or "request failed")


def dec_str(amount_int, decimals):
    """Exact decimal string; int math only, no float anywhere."""
    q = Decimal(int(amount_int)).scaleb(-decimals)
    return format(q, "f")


# ---------------------------------------------------------------- BTC
def btc_wallet(addr):
    info = http_json("https://blockstream.info/api/address/" + urllib.parse.quote(addr))
    txs = http_json("https://blockstream.info/api/address/%s/txs" % urllib.parse.quote(addr))
    funded = info["chain_stats"]["funded_txo_sum"]
    spent = info["chain_stats"]["spent_txo_sum"]
    balance = funded - spent
    rows = []
    for tx in txs[:50]:
        out_val = sum(o["value"] for o in tx.get("vout", []) if o.get("scriptpubkey_address") == addr)
        in_val = sum(i.get("prevout", {}).get("value", 0) for i in tx.get("vin", [])
                     if i.get("prevout", {}).get("scriptpubkey_address") == addr)
        rows.append({
            "txid": tx["txid"],
            "direction": "in" if out_val >= in_val else "out",
            "amount_min": out_val if out_val >= in_val else in_val,
            "amount": dec_str(out_val if out_val >= in_val else in_val, 8),
            "block_time": tx.get("status", {}).get("block_time"),
            "confirmed": bool(tx.get("status", {}).get("confirmed")),
        })
    return {
        "chain": "btc", "address": addr, "balance_min": balance, "balance": dec_str(balance, 8),
        "unit": "sats", "tx_count": info["chain_stats"]["tx_count"], "txs": rows,
    }


# ---------------------------------------------------------------- ETH
ETH_RPCS = (
    "https://ethereum.publicnode.com",
    "https://eth.drpc.org",
    "https://cloudflare-eth.com",
)


def eth_balance_wei(addr):
    """Keyless public RPCs; they rate-limit without warning, so try a few."""
    payload = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "eth_getBalance",
                          "params": [addr, "latest"]}).encode()
    last = "no rpc answered"
    for url in ETH_RPCS:
        try:
            req = urllib.request.Request(url, data=payload,
                                         headers={**UA, "Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
                body = json.loads(r.read().decode("utf-8", "replace"))
            if body.get("result"):
                return int(body["result"], 16)
            last = "%s: %s" % (url, (body.get("error") or {}).get("message", "empty result")[:60])
        except Exception as e:  # noqa: BLE001
            last = "%s: %s" % (url, type(e).__name__)
    raise RuntimeError("eth balance unavailable (%s)" % last)


def eth_wallet(addr):
    wei = eth_balance_wei(addr)
    txs = http_json("https://eth.blockscout.com/api/v2/addresses/%s/transactions" % urllib.parse.quote(addr))
    rows = []
    for item in (txs.get("items") or [])[:50]:
        val = int(item.get("value", "0") or 0)
        rows.append({
            "txid": item.get("hash"),
            "direction": "out" if (item.get("from") or {}).get("hash", "").lower() == addr.lower() else "in",
            "amount_min": val,
            "amount": dec_str(val, 18),
            "block_time": item.get("timestamp"),
            "confirmed": True,
        })
    return {
        "chain": "eth", "address": addr, "balance_min": wei, "balance": dec_str(wei, 18),
        "unit": "wei", "tx_count": len(rows), "txs": rows,
    }


# ---------------------------------------------------------------- TRX
def trx_wallet(addr):
    acct = http_json("https://api.trongrid.io/v1/accounts/" + urllib.parse.quote(addr))
    data = (acct.get("data") or [{}])[0]
    bal = int(data.get("balance", 0) or 0)
    trc20 = []
    for t in data.get("trc20", []) or []:
        for token_id, raw in t.items():
            trc20.append({"token_contract": token_id, "raw": str(raw)})
    txs = http_json("https://api.trongrid.io/v1/accounts/%s/transactions?limit=50" % urllib.parse.quote(addr))
    rows = []
    for item in (txs.get("data") or [])[:50]:
        raw = item.get("raw_data", {}) or {}
        contracts = raw.get("contract") or [{}]
        c0 = contracts[0] if contracts else {}
        val = c0.get("parameter", {}).get("value", {}).get("amount", 0)
        rows.append({
            "txid": item.get("txID"),
            "direction": "in" if c0.get("parameter", {}).get("value", {}).get("to_address") == addr else "out",
            "amount_min": int(val or 0),
            "amount": dec_str(int(val or 0), 6),
            "block_time": raw.get("timestamp"),
            "confirmed": bool(item.get("ret", [{}])[0].get("contractRet") == "SUCCESS"),
        })
    return {
        "chain": "trx", "address": addr, "balance_min": bal, "balance": dec_str(bal, 6),
        "unit": "sun", "tx_count": len(rows), "trc20": trc20, "txs": rows,
    }


HANDLERS = {"btc": btc_wallet, "eth": eth_wallet, "trx": trx_wallet}


def guess_chain(addr):
    a = addr.strip()
    if a.startswith("0x") and len(a) == 42:
        return "eth"
    if a.startswith("T") and len(a) == 34:
        return "trx"
    return "btc"


def load_wallets(path):
    out = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.split("#")[0].strip()
            if not line:
                continue
            if ":" in line and line.split(":", 1)[0].lower() in HANDLERS:
                chain, addr = line.split(":", 1)
                out.append((chain.lower(), addr.strip()))
            else:
                out.append((guess_chain(line), line))
    return out


DEMO = [
    ("btc", "bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97"),
    ("btc", "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"),
    ("eth", "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"),
    ("eth", "0x28C6c06298d514Db089934071355E5743bf21d60"),
    ("trx", "TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7"),
]


def main(argv):
    ap = argparse.ArgumentParser()
    ap.add_argument("--wallets")
    ap.add_argument("--out", default="report.json")
    ap.add_argument("--csv")
    ap.add_argument("--demo", action="store_true")
    ap.add_argument("--quiet", action="store_true")
    a = ap.parse_args(argv)

    if a.demo:
        targets = DEMO
    elif a.wallets:
        targets = load_wallets(a.wallets)
    else:
        ap.error("need --wallets FILE or --demo")

    report = {"generated_at": int(time.time()), "chains": {}, "wallets": [], "errors": []}
    for chain, addr in targets:
        try:
            row = HANDLERS[chain](addr)
            report["wallets"].append(row)
            c = CHAINS[chain]
            print("%-4s %-44s %s %s (= %s %s)  txs %d"
                  % (c["label"], addr[:44], row["balance"], c["label"],
                     row["balance_min"], c["unit"], len(row["txs"])))
        except Exception as e:  # noqa: BLE001
            report["errors"].append({"chain": chain, "address": addr, "error": str(e)[:120]})
            print("%-4s %-46s ERROR %s" % (chain.upper(), addr[:46], str(e)[:80]))

    for chain in CHAINS:
        rows = [w for w in report["wallets"] if w["chain"] == chain]
        if rows:
            report["chains"][chain] = {
                "wallets": len(rows),
                "balance_min_total": str(sum(int(w["balance_min"]) for w in rows)),
                "unit": CHAINS[chain]["unit"],
            }

    with open(a.out, "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2, ensure_ascii=False)
    print("json ->", a.out)

    if a.csv:
        with open(a.csv, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["chain", "address", "txid", "direction", "amount", "amount_min", "block_time", "confirmed"])
            for row in report["wallets"]:
                for tx in row["txs"]:
                    w.writerow([row["chain"], row["address"], tx["txid"], tx["direction"],
                                tx["amount"], tx["amount_min"], tx["block_time"], tx["confirmed"]])
        print("csv  ->", a.csv)
    if report["errors"]:
        print("errors:", len(report["errors"]))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))