#!/usr/bin/env python3
"""
Number Cruncher board solver — counts how many distinct valid equations a hex board admits.

Written for ruthheasman's Number Cruncher (numbercrunchermath.com) so the board generator
can ask "are there at least N solutions?" instead of "is there one?".

Rules encoded here, and where each one comes from:
  - Board: hexagons on axial coordinates (q, r); the shipped game uses radius 2 (19 tiles).
  - Tile values: single digits 0-9.
  - A player selects tiles one at a time; each tile's digit is APPENDED to the formula string,
    so selecting 1 then 2 reads as the number 12. (game source: selectTile → currentFormula + value)
  - Operators + - x / = ( ) are buttons, not tiles; the player chooses them.
    (ruthheasman, 2026-08-27: "The user picks the operator … an equation must have an equals
    sign in it, and can include brackets.")
  - Hard mode: only one operator is available for the whole level.  (--ops "+")
  - All selected hexagons must be touching each other as a GROUP — any order, any combination.
    (ruthheasman, 2026-08-27; game source validateHexagonConnectivity: BFS over the selected set,
    neighbours = the six axial directions.)
  - Validity: exactly one "=", both sides evaluate to the same value, no empty parentheses,
    no leading/trailing operator. (game source: validation function)
  - Arithmetic here is EXACT (fractions), so 1/3 = 2/6 counts and nothing depends on float luck.
    Division by zero is invalid.  Leading zeros ("05") are invalid — the game's own evaluator
    would reject them.

What "distinct" means here (my definition — say if you want a different one):
  - A SOLUTION is a set of tiles that admits at least one valid equation. Two equations that use
    the same tiles count once. That is the number to gate a board on: it says how many different
    places on the board a player could find something.
  - --list also prints the equations themselves (one per tile set, first found), so you can eyeball
    what a board offers.
  - Equations with no operator at all (5 = 5, 12 = 12) are NOT counted by default; --allow-identity
    counts them.

Usage:
  solver.py board.json                  # board from the game's hexTiles JSON or a simple list
  solver.py --random 200 --seed 1       # deal boards the way the game does, print the distribution
  solver.py board.json --list --max-tiles 5 --ops "+-x/"
  solver.py board.json --must-include=0,0     # pivot rule: only equations that use tile (0,0)
  solver.py --random 50 --per-tile --ops "/"  # worst tile per board on a divide-only level

What the numbers look like (my measurement, 2026-08-28, boards dealt the game's way, 4 tiles max):
  - all four operators: 150-220 solutions per fresh board; the worst single tile still has 9+.
  - "+" only: 80-120.   "-" only: 80-120.   "x" only / "/" only: 28-72.
  - "/" only, per tile: most boards have at least one tile with 0-2 solutions. That is where a
    board can actually be thin — a single-operator divide level with a pivot tile.

Board JSON accepted in either shape:
  {"0,0": {"coord": {"q":0,"r":0}, "value": 7}, ...}      # the game's hexTiles object as-is
  [{"q":0,"r":0,"v":7}, ...]                                # or a plain list
"""
import argparse, itertools, json, random, sys
from fractions import Fraction
from functools import lru_cache

NEIGHBOURS = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, -1), (-1, 1)]


# ── board ────────────────────────────────────────────────────────────────────────────────
def load_board(obj):
    """Return {(q,r): digit}. Accepts the game's hexTiles dict or a list of {q,r,v}."""
    tiles = {}
    if isinstance(obj, dict):
        for k, t in obj.items():
            c = t.get("coord") or {}
            q, r = (c.get("q"), c.get("r")) if c else map(int, k.split(","))
            tiles[(int(q), int(r))] = int(t["value"])
    else:
        for t in obj:
            tiles[(int(t["q"]), int(t["r"]))] = int(t.get("v", t.get("value")))
    return tiles


def deal_board(radius=2, rng=random):
    """Deal a board the way the game does: digits 0-9 from a shuffled deck, reshuffled when empty."""
    deck = []
    tiles = {}
    for q in range(-radius, radius + 1):
        for r in range(max(-radius, -q - radius), min(radius, -q + radius) + 1):
            if not deck:
                deck = list(range(10)); rng.shuffle(deck)
            tiles[(q, r)] = deck.pop()
    return tiles


def connected_subsets(tiles, max_size):
    """All connected sets of tile coordinates with 1 <= size <= max_size (each set once)."""
    cells = sorted(tiles)
    index = {c: i for i, c in enumerate(cells)}
    adj = {c: [n for d in NEIGHBOURS if (n := (c[0] + d[0], c[1] + d[1])) in tiles] for c in cells}
    out = set()

    def grow(current, frontier, min_index):
        out.add(frozenset(current))
        if len(current) == max_size:
            return
        # candidates: neighbours of the set, with index > root index (each set generated from its
        # lowest-index cell, so no duplicates across roots)
        cand = sorted({n for c in current for n in adj[c] if n not in current and index[n] > min_index})
        for i, n in enumerate(cand):
            grow(current | {n}, None, min_index)
    for c in cells:
        grow(frozenset([c]), None, index[c])
    # dedupe: the same set can be grown by different orders; frozenset handles it
    return [s for s in out if len(s) >= 1]


# ── expressions ──────────────────────────────────────────────────────────────────────────
def numbers_from_sequence(digits, max_len):
    """Ways to group an ordered digit sequence into numbers (concatenation), no leading zeros."""
    n = len(digits)
    res = []

    def rec(i, acc):
        if i == n:
            res.append(tuple(acc)); return
        for j in range(i + 1, min(n, i + max_len) + 1):
            chunk = digits[i:j]
            if len(chunk) > 1 and chunk[0] == 0:
                break
            rec(j, acc + [int("".join(map(str, chunk)))])
    rec(0, [])
    return res


def make_values(ops):
    @lru_cache(maxsize=None)
    def values(nums):
        """Every value (and one expression string for it) reachable from the ordered numbers with
        the allowed binary operators and any bracketing."""
        if len(nums) == 1:
            return {Fraction(nums[0]): str(nums[0])}
        out = {}
        for k in range(1, len(nums)):
            L, R = values(nums[:k]), values(nums[k:])
            for lv, ls in L.items():
                for rv, rs in R.items():
                    for op in ops:
                        if op == "+": v = lv + rv
                        elif op == "-": v = lv - rv
                        elif op == "x": v = lv * rv
                        elif op == "/":
                            if rv == 0: continue
                            v = lv / rv
                        else: continue
                        if v not in out:
                            ls_ = f"({ls})" if len(nums[:k]) > 1 else ls
                            rs_ = f"({rs})" if len(nums[k:]) > 1 else rs
                            out[v] = f"{ls_} {op} {rs_}"
        return out
    return values


def solve(tiles, ops="+-x/", max_tiles=5, max_num_len=2, allow_identity=False, must_include=None):
    """Return (count_of_tile_sets_with_a_solution, {tile_set: example_equation})."""
    values = make_values(ops)
    found = {}
    for s in connected_subsets(tiles, max_tiles):
        if len(s) < 2 or (must_include is not None and must_include not in s):
            continue
        cells = sorted(s)
        hit = None
        for perm in itertools.permutations(cells):
            digits = [tiles[c] for c in perm]
            for nums in numbers_from_sequence(digits, max_num_len):
                if len(nums) < 2:
                    continue
                for k in range(1, len(nums)):
                    left, right = nums[:k], nums[k:]
                    if not allow_identity and len(left) == 1 and len(right) == 1:
                        continue
                    L, R = values(left), values(right)
                    common = L.keys() & R.keys()
                    if common:
                        v = next(iter(common))
                        hit = f"{L[v]} = {R[v]}"
                        break
                if hit: break
            if hit: break
        if hit:
            found[s] = hit
    return len(found), found


# ── cli ──────────────────────────────────────────────────────────────────────────────────
def fmt_board(tiles):
    return " ".join(f"({q},{r})={v}" for (q, r), v in sorted(tiles.items()))


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("board", nargs="?", help="board JSON file (see docstring); omit with --random")
    ap.add_argument("--random", type=int, default=0, help="deal N boards the game's way and report")
    ap.add_argument("--seed", type=int, default=None)
    ap.add_argument("--ops", default="+-x/", help='allowed operators, e.g. "+" for hard mode')
    ap.add_argument("--max-tiles", type=int, default=5, help="largest equation to look for (tiles)")
    ap.add_argument("--max-num-len", type=int, default=2, help="longest number by concatenation")
    ap.add_argument("--min", type=int, default=3, help="a board is THIN below this many solutions")
    ap.add_argument("--allow-identity", action="store_true", help="count 5 = 5 style equations")
    ap.add_argument("--list", action="store_true", help="print one equation per solution")
    ap.add_argument("--must-include", metavar="q,r", help="only count equations that use this tile (pivot rule)")
    ap.add_argument("--per-tile", action="store_true", help="with --random: report the WORST tile's count per board")
    a = ap.parse_args()

    if a.random:
        rng = random.Random(a.seed)
        hist = {}
        thin = 0
        for i in range(a.random):
            b = deal_board(rng=rng)
            if a.per_tile:
                n = min(solve(b, a.ops, a.max_tiles, a.max_num_len, a.allow_identity, must_include=c)[0] for c in b)
            else:
                n, _ = solve(b, a.ops, a.max_tiles, a.max_num_len, a.allow_identity)
            hist[n] = hist.get(n, 0) + 1
            thin += n < a.min
        print(json.dumps({"boards": a.random, "ops": a.ops, "max_tiles": a.max_tiles, "per_tile_worst": a.per_tile,
                          "thin_below": a.min, "thin_boards": thin,
                          "solutions_histogram": dict(sorted(hist.items()))}, indent=1))
        return

    if not a.board:
        ap.error("give a board file or --random N")
    with open(a.board) as f:
        tiles = load_board(json.load(f))
    mi = tuple(int(x) for x in a.must_include.split(",")) if a.must_include else None
    n, found = solve(tiles, a.ops, a.max_tiles, a.max_num_len, a.allow_identity, must_include=mi)
    out = {"tiles": len(tiles), "ops": a.ops, "max_tiles": a.max_tiles, "must_include": a.must_include,
           "solutions": n, "thin": n < a.min}
    if a.list:
        out["equations"] = [{"tiles": [list(c) for c in sorted(s)], "equation": e}
                            for s, e in sorted(found.items(), key=lambda kv: (len(kv[0]), sorted(kv[0])))]
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
