#!/usr/bin/env python3
"""Reproducible printable word-bingo boards for a fictional community gathering.

Python 3, standard library only.  Writes into the output directory:
    board_A.svg ... board_D.svg   A4 portrait boards, 210 x 297 mm page units
    caller_list.csv               the 30-word caller pool with call order
    manifest.json                 exact cells + validation results

Usage:
    python3 make_bingo.py OUTPUT_DIR
"""

from __future__ import annotations

import csv
import json
import random
import sys
from pathlib import Path

SEED = 20261118
POOL = (
    "map river lantern boat bridge cloud leaf tent compass basket "
    "pebble flower tree kite bench moon star sun rainbow acorn "
    "pinecone cabin waterfall island meadow valley bird butterfly fox owl"
).split()
SIZE = 5
BOARD_COUNT = 4
LABELS = ["A", "B", "C", "D"]
FREE = "FREE"
CENTER = (2, 2)                     # zero-based row, column -> the 13th cell
WORDS_PER_BOARD = SIZE * SIZE - 1   # 24

# --- page geometry, all numbers in millimetres (1 user unit = 1 mm) ----------
PAGE_W, PAGE_H = 210.0, 297.0
MARGIN = 15.0
GRID_TOP = 58.0
CELL = (PAGE_W - 2 * MARGIN) / SIZE          # 36.0 mm

INK, MUTED = "#2b3a42", "#71808a"
RULE, PAPER = "#d9d3c7", "#fcfbf8"
ACCENT, ACCENT_SOFT = "#5c8374", "#e9f0ec"
FONT = "'Helvetica Neue', Helvetica, Arial, 'DejaVu Sans', sans-serif"


# --- boards ----------------------------------------------------------------
def build_boards(seed: int = SEED, count: int = BOARD_COUNT) -> list:
    """Four boards from one seeded stream; redraw only on an identical grid."""
    rng = random.Random(seed)
    boards, seen = [], set()
    while len(boards) < count:
        words = rng.sample(POOL, WORDS_PER_BOARD)
        rng.shuffle(words)
        it = iter(words)
        cells = [
            [FREE if (r, c) == CENTER else next(it) for c in range(SIZE)]
            for r in range(SIZE)
        ]
        key = tuple(tuple(row) for row in cells)
        if key in seen:
            continue
        seen.add(key)
        boards.append(cells)
    return boards


# --- validation ------------------------------------------------------------
def validate(boards: list) -> dict:
    pool_set = set(POOL)
    per_board, keys = [], []
    for label, cells in zip(LABELS, boards):
        flat = [w for row in cells for w in row]
        words = [w for w in flat if w != FREE]
        per_board.append({
            "board": label,
            "word_count": len(words),
            "distinct_word_count": len(set(words)),
            "all_words_in_pool": all(w in pool_set for w in words),
            "no_repeats": len(set(words)) == len(words) == WORDS_PER_BOARD,
            "center_is_free": cells[CENTER[0]][CENTER[1]] == FREE,
            "free_cell_count": flat.count(FREE),
            "free_cell_at_row_col_1based": [CENTER[0] + 1, CENTER[1] + 1],
            "passed": (all(w in pool_set for w in words)
                       and len(set(words)) == len(words) == WORDS_PER_BOARD
                       and cells[CENTER[0]][CENTER[1]] == FREE
                       and flat.count(FREE) == 1),
        })
        keys.append(tuple(flat))

    pairwise = []
    for i in range(len(keys)):
        for j in range(i + 1, len(keys)):
            differing = sum(1 for a, b in zip(keys[i], keys[j]) if a != b)
            shared = [a for a in keys[i] if a in keys[j] and a != FREE]
            pairwise.append({
                "boards": [LABELS[i], LABELS[j]],
                "differing_cells": differing,
                "of_cells": SIZE * SIZE,
                "shared_words": len(shared),
            })

    distinct = len(set(keys)) == len(keys)
    passed = distinct and all(b["passed"] for b in per_board)
    return {
        "passed": passed,
        "checks": {
            "pool_size_is_30": len(POOL) == 30 and len(set(POOL)) == 30,
            "every_word_in_pool": all(b["all_words_in_pool"] for b in per_board),
            "within_board_unique": all(b["no_repeats"] for b in per_board),
            "fixed_center_free": all(b["center_is_free"] and b["free_cell_count"] == 1
                                     for b in per_board),
            "board_arrangements_distinct": distinct,
        },
        "per_board": per_board,
        "pairwise": pairwise,
    }


# --- SVG -------------------------------------------------------------------
def esc(text: str) -> str:
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def word_font(word: str) -> float:
    n = len(word)
    return 5.2 if n <= 6 else (4.8 if n <= 8 else 4.4)


def board_svg(cells: list, label: str, seed: int = SEED) -> str:
    x0, y0 = MARGIN, GRID_TOP
    out = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        f'<svg xmlns="http://www.w3.org/2000/svg" width="210mm" height="297mm" '
        f'viewBox="0 0 210 297" version="1.1">',
        "<title>Community Word Bingo - board " + label + "</title>",
        "<style>",
        f"  text {{ font-family: {FONT}; fill: {INK}; }}",
        f"  .title {{ font-size: 7.6px; font-weight: 700; letter-spacing: 1px; }}",
        f"  .sub   {{ font-size: 3.5px; fill: {MUTED}; letter-spacing: 0.4px; }}",
        f"  .tag   {{ font-size: 3.7px; font-weight: 700; letter-spacing: 1.1px; text-anchor: end; }}",
        f"  .word  {{ font-size: 4.2px; text-anchor: middle; }}",
        f"  .free  {{ font-size: 4.4px; font-weight: 700; letter-spacing: 0.6px; "
        f"text-anchor: middle; fill: {ACCENT}; }}",
        f"  .foot  {{ font-size: 3.0px; fill: {MUTED}; }}",
        "</style>",
        f'<rect width="210" height="297" fill="{PAPER}"/>',
        # header (every string measured to stay inside the 180 mm text column)
        '<text class="title" x="15" y="25">COMMUNITY WORD BINGO</text>',
        f'<text class="tag" x="195" y="25">BOARD {label}</text>',
        f'<text class="sub" x="15" y="33">A fictional neighbourhood gathering '
        f'\u00b7 free to attend \u00b7 no prizes, no money</text>',
        f'<rect x="15" y="37.5" width="180" height="0.5" fill="{ACCENT}"/>',
        f'<text class="sub" x="15" y="45.5">5 \u00d7 5 grid \u00b7 24 different caller '
        f'words \u00b7 FREE in the centre</text>',
        f'<text class="sub" x="195" y="45.5" text-anchor="end">seed {seed}</text>',
    ]
    # grid
    for r in range(SIZE):
        for c in range(SIZE):
            x = x0 + c * CELL
            y = y0 + r * CELL
            is_free = (r, c) == CENTER
            fill = ACCENT_SOFT if is_free else "#ffffff"
            out.append(f'<rect x="{x:.2f}" y="{y:.2f}" width="{CELL:.2f}" '
                       f'height="{CELL:.2f}" fill="{fill}" stroke="{RULE}" '
                       f'stroke-width="0.4"/>')
            cx = x + CELL / 2
            word = cells[r][c]
            if is_free:
                out.append(f'<text class="free" x="{cx:.2f}" '
                           f'y="{y + CELL / 2 + 1.55:.2f}">{FREE}</text>')
            else:
                fs = word_font(word)
                out.append(f'<text class="word" x="{cx:.2f}" '
                           f'y="{y + CELL / 2 + fs * 0.35:.2f}" '
                           f'font-size="{fs}">{esc(word)}</text>')
    out.append(f'<rect x="{x0}" y="{y0}" width="{SIZE * CELL}" height="{SIZE * CELL}" '
               f'fill="none" stroke="{INK}" stroke-width="0.7"/>')
    # footer
    foot_top = y0 + SIZE * CELL + 11
    out.append(f'<rect x="15" y="{foot_top - 7:.2f}" width="180" height="0.3" '
               f'fill="{RULE}"/>')
    out.append(f'<text class="foot" x="15" y="{foot_top:.2f}">Seed {seed} '
               f'\u00b7 make_bingo.py \u00b7 board {label} of 4 \u00b7 24 words plus '
               f'FREE centre</text>')
    out.append(f'<text class="foot" x="15" y="{foot_top + 6:.2f}">Printable example for a '
               f'fictional free community event.</text>')
    out.append(f'<text class="foot" x="15" y="{foot_top + 12:.2f}">Different boards do not '
               f'guarantee different winners; this is not a fairness or gambling claim.</text>')
    out.append("</svg>")
    return "\n".join(out) + "\n"


# --- writers ---------------------------------------------------------------
def write_csv(path: Path) -> None:
    with path.open("w", newline="", encoding="utf-8") as fh:
        writer = csv.writer(fh, lineterminator="\n")
        writer.writerow(["call_order", "word"])
        for i, word in enumerate(POOL, start=1):
            writer.writerow([i, word])


def main(argv: list) -> int:
    if len(argv) != 2:
        print("usage: python3 make_bingo.py OUTPUT_DIR", file=sys.stderr)
        return 2
    out = Path(argv[1])
    out.mkdir(parents=True, exist_ok=True)

    boards = build_boards()
    report = validate(boards)

    files = []
    for label, cells in zip(LABELS, boards):
        name = f"board_{label}.svg"
        (out / name).write_text(board_svg(cells, label), encoding="utf-8")
        files.append(name)
    write_csv(out / "caller_list.csv")

    manifest = {
        "title": "Community Word Bingo - reproducible printable example",
        "generator": {"script": "make_bingo.py", "language": "Python 3",
                      "dependencies": "standard library only", "seed": SEED},
        "spec": {
            "boards": BOARD_COUNT,
            "grid": {"rows": SIZE, "columns": SIZE},
            "words_per_board": WORDS_PER_BOARD,
            "free_cell": {"label": FREE, "row_zero_based": CENTER[0],
                          "column_zero_based": CENTER[1]},
            "page": {"units": "mm", "width": PAGE_W, "height": PAGE_H,
                     "orientation": "portrait"},
            "fonts": {"family": FONT, "note": "plain <text> elements, text stays editable"},
        },
        "caller_pool": POOL,
        "boards": [
            {"id": label, "file": f"board_{label}.svg", "cells": cells}
            for label, cells in zip(LABELS, boards)
        ],
        "validation": report,
        "notes": [
            "Every board holds 24 different words drawn from the 30-word pool, "
            "with one FREE cell fixed at row 3, column 3.",
            "The four complete grid arrangements are different from one another.",
            "Only internal consistency and reproducibility are checked here. "
            "Distinct boards do not guarantee distinct winners, and this example "
            "makes no claim about fairness or gambling outcomes.",
        ],
    }
    (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n",
                                       encoding="utf-8")

    print("wrote:", ", ".join(files + ["caller_list.csv", "manifest.json"]),
          "->", out)
    print("validation passed:", report["passed"])
    for check, ok in report["checks"].items():
        print(f"  [{'ok' if ok else 'FAIL'}] {check}")
    return 0 if report["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))

