#!/usr/bin/env python3
"""mint_watcher.py — BSC free-mint watcher for any ERC-721 / mint ladder.

Give it a contract address and it watches totalMinted / totalSupply,
printing every new mint with its token ID and owner address.

No dependencies beyond Python 3.8+ standard library.
Runs anywhere: laptop, VPS, or another agent's sandbox.

Usage:
    python3 mint_watcher.py --contract 0x0c25ACf82AcBcAA6ab33364Ec4ad60b78A4f6644
    python3 mint_watcher.py --contract 0x... --once            # single check
    python3 mint_watcher.py --contract 0x... --interval 300    # check every 5 min
    python3 mint_watcher.py --contract 0x... --baseline 200    # start counting at 200

State is kept in <contract>.baseline.json next to the script, so a restart
does not re-report mints it already saw.

This script is the content of the "Mint Watcher" code-NFT: whoever holds
the NFT holds this tool. It reads the chain only; it never signs anything.
"""
import argparse
import json
import os
import sys
import time
import urllib.request

RPCS = [
    "https://bsc-dataseed1.bnbchain.org",
    "https://bsc-dataseed3.bnbchain.org",
    "https://bsc-dataseed4.bnbchain.org",
    "https://bsc-dataseed.bnbchain.org",
    "https://bsc.publicnode.com",
]

# function selectors
TOTAL_MINTED = "0xa2309ff8"   # totalMinted() — our ladder contracts
TOTAL_SUPPLY = "0x18160ddd"   # totalSupply() — standard ERC-721
OWNER_OF = "0x6352211e"       # ownerOf(uint256)


def rpc_call(url, method, params, timeout=10):
    body = json.dumps({
        "jsonrpc": "2.0", "id": 1, "method": method, "params": params,
    }).encode()
    req = urllib.request.Request(url, data=body,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.load(resp)


def eth_call(to, data):
    """Try each RPC in turn; return raw hex result or raise."""
    last_err = None
    for url in RPCS:
        try:
            out = rpc_call(url, "eth_call",
                           [{"to": to, "data": data}, "latest"])
            if "result" in out and out["result"]:
                return out["result"]
            last_err = out.get("error", out)
        except Exception as exc:  # noqa: BLE001 - try next RPC
            last_err = exc
    raise RuntimeError(f"all RPCs failed: {last_err}")


def total_minted(contract):
    """totalMinted() if present, else totalSupply()."""
    for sel in (TOTAL_MINTED, TOTAL_SUPPLY):
        try:
            return int(eth_call(contract, sel), 16)
        except Exception:  # noqa: BLE001 - try next selector
            continue
    raise RuntimeError("contract has neither totalMinted() nor totalSupply()")


def owner_of(contract, token_id):
    data = OWNER_OF + f"{token_id:064x}"
    return "0x" + eth_call(contract, data)[-40:]


def short(addr):
    return addr[:6] + "..." + addr[-4:]


def check(contract, baseline):
    """Return (total, [new mints]) without touching any state file."""
    total = total_minted(contract)
    new = []
    for token_id in range(baseline + 1, total + 1):
        try:
            new.append({"id": token_id, "owner": owner_of(contract, token_id)})
        except Exception as exc:  # noqa: BLE001 - report what we can
            new.append({"id": token_id, "owner": f"? ({exc})"})
    return total, new


def main():
    ap = argparse.ArgumentParser(description="Watch new mints on a BSC contract.")
    ap.add_argument("--contract", required=True, help="NFT contract address")
    ap.add_argument("--once", action="store_true", help="check once and exit")
    ap.add_argument("--interval", type=int, default=300,
                    help="seconds between checks (default 300)")
    ap.add_argument("--baseline", type=int, default=None,
                    help="token id to start counting after (default: current total)")
    args = ap.parse_args()

    contract = args.contract
    state_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                              f"{contract.lower()}.baseline.json")
    baseline = args.baseline
    if baseline is None and os.path.exists(state_file):
        baseline = json.load(open(state_file))["total"]

    while True:
        try:
            total, new = check(contract, baseline if baseline is not None else 0)
        except Exception as exc:  # noqa: BLE001 - keep watching
            print(f"[error] {exc}", flush=True)
            if args.once:
                return 1
            time.sleep(args.interval)
            continue

        if baseline is None:
            print(f"[init] {short(contract)} total={total} "
                  f"(baseline set, watching for new mints)", flush=True)
        elif new:
            for m in new:
                print(f"[mint] #{m['id']} -> {short(m['owner'])}", flush=True)
            print(f"[total] {total}", flush=True)
        else:
            print(f"[ok] no new mints, total={total}", flush=True)

        baseline = total
        json.dump({"total": total}, open(state_file, "w"))
        if args.once:
            return 0
        time.sleep(args.interval)


if __name__ == "__main__":
    sys.exit(main())
