"""Final figures for the featured wallet, excluding its external transfer.

Usage: python3 final_numbers.py [evidence_dir] [sol_usd]
"""
import datetime, gzip, json, os, statistics, sys
from decimal import Decimal
from analyze import analyse

E = sys.argv[1] if len(sys.argv) > 1 else "wallet-evidence"
P = Decimal(sys.argv[2]) if len(sys.argv) > 2 else Decimal("117.53")
WALLET = "MriyaNN8TMp6qRWjfr723PK7xgQK7yCt7Kg2v2PQu7X"
EXTERNAL_TRANSFERS = {"5RoMKyu4a5FVRAh8"}  # 10.02 SOL sent to related wallet ForJ...

src = f"{E}/transactions.jsonl"
lines = open(src) if os.path.exists(src) else gzip.open(src + ".gz", "rt")
rows = [analyse(json.loads(l)) for l in lines if l.strip()]
rows = [r for r in rows if r["payer"] == WALLET and r["signature"][:16] not in EXTERNAL_TRANSFERS]
usd = lambda r: float(r["stableDelta"] + r["solEquivalentDelta"] * P)
ok = sorted((usd(r) for r in rows if r["success"]), reverse=True)
failed = [usd(r) for r in rows if not r["success"]]
net = sum(ok) + sum(failed)
times = [r["blockTime"] for r in rows]
hours = (max(times) - min(times)) / 3600
costs = {k: float(sum(r[k] for r in rows)) for k in ("baseFee", "priorityFee", "jitoTip")}
inclusion_usd = sum(costs.values()) * float(P)
out = {
    "solUsd": float(P),
    "window": [datetime.datetime.fromtimestamp(t, datetime.UTC).isoformat() for t in (min(times), max(times))],
    "transactions": len(rows), "succeeded": len(ok), "failed": len(failed),
    "netUsd": round(net, 2), "netSol": round(net / float(P), 3), "netUsdPerHour": round(net / hours, 2),
    "successfulUsd": round(sum(ok), 2), "failedCostUsd": round(sum(failed), 2),
    "medianSuccessfulUsd": round(statistics.median(ok), 4), "meanSuccessfulUsd": round(statistics.mean(ok), 4),
    "bestUsd": round(ok[0], 2), "losingSuccessful": sum(v < 0 for v in ok),
    "top1SharePct": round(100 * ok[0] / net, 1), "top10SharePct": round(100 * sum(ok[:10]) / net, 1),
    "inclusionCostsSol": {k: round(v, 4) for k, v in costs.items()},
    "inclusionCostsUsd": round(inclusion_usd, 2), "inclusionShareOfGrossPct": round(100 * inclusion_usd / (net + inclusion_usd), 1),
}
json.dump(out, open(f"{E}/final_numbers.json", "w"), indent=2)
print(json.dumps(out, indent=2))
