"""verify_block.py — CLI a buyer can run to prove their merch block is real.

Usage:  python3 verify_block.py bitcoinaire 3
        (verifies block #3 in the Bitcoinaire chain against the public ledger)

Fetches the public per-chain JSON from the store, walks the hash chain from
genesis to the given block, and independently recomputes each block's hash.
"""

import hashlib
import json
import sys
import urllib.request

LEDGER_BASE = "https://twentyone-book-store.pages.dev/ledger"


def hash_block(chain_id, block_no, ts, price_cents, buyer, prev_hash):
    payload = json.dumps({
        "chain": chain_id, "n": block_no, "ts": round(ts, 3),
        "price": price_cents, "buyer": buyer, "prev": prev_hash,
    }, sort_keys=True)
    return hashlib.sha256(payload.encode()).hexdigest()


def verify(chain_slug: str, my_block_no: int, local_file: str = None):
    if local_file:
        chain = json.load(open(local_file))
    else:
        safe = f"merch_{chain_slug}_tee"
        url = f"{LEDGER_BASE}/chains/{safe}.json"
        print(f"Fetching {url}")
        chain = json.loads(urllib.request.urlopen(url).read())

    print(f"\n=== Chain: {chain['chain_id']} ===")
    print(f"   {chain['block_count']} of {chain['cap']} blocks mined")
    print(f"   Tip hash: {chain['tip_hash']}\n")

    prev = "0" * 64
    verified = 0
    target_hash = None
    for b in chain["blocks"]:
        expect = hash_block(chain["chain_id"], b["block_no"], b["ts"],
                            b["price_cents"], b["buyer"], b["prev_hash"])
        if expect != b["hash"]:
            print(f"BROKEN at block #{b['block_no']}: hash mismatch")
            return False
        if b["prev_hash"] != prev:
            print(f"BROKEN at block #{b['block_no']}: prev_hash mismatch")
            return False
        prev = b["hash"]
        verified += 1
        if b["block_no"] == my_block_no:
            target_hash = b["hash"]
            print(f"   Your block #{my_block_no}:")
            print(f"     time:  {b['ts']}")
            print(f"     price: ${b['price_cents']/100:.2f}")
            print(f"     batch: {b['batch']}")
            print(f"     hash:  {b['hash']}")
            print(f"     prev:  {b['prev_hash']}")

    print(f"\n   Verified {verified} blocks. Chain intact.")
    if target_hash is None:
        print(f"   Warning: block #{my_block_no} not found in this chain")
        return False
    print(f"\n   Your block hash is anchored to Bitcoin via /ledger/manifest.json.ots")
    print(f"   Run:  ots verify manifest.json  (with the .ots file)")
    return True


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("usage: verify_block.py <chain-slug> <block-no> [local-json-file]")
        sys.exit(1)
    ok = verify(sys.argv[1], int(sys.argv[2]),
                sys.argv[3] if len(sys.argv) > 3 else None)
    sys.exit(0 if ok else 1)
