"""The spherical federation of echosahedra at levels up to 13, composed with little memory.

`boards.compose` builds the board with global arrays (about 1.8 KB per cell at its peak). This module builds the
same board level by level with row chunks and int32 indices:

* the geodesic tower keeps, per face, its vertices `f`, the neighbour across each edge `nbr` and that
  neighbour's edge slot `nslot`. A face's children and their neighbours follow from the parent's (outward
  faces stay outward, which every level checks), so no global sort is needed. A new midpoint takes the number
  of its first use, as in `boards._refine`: the edge's owner is the face with the smaller index.
* vertex coordinates use the same NumPy expressions as `boards` row by row (midpoint sum and einsum norm,
  `_clean` twice per level), so every coordinate is bit-identical;
* each cell scores the twelve port directions toward each neighbour as `boards.compose` does, takes the best
  port and repairs clashes with the same assignment over its three seams in edge-key order. A compiled kernel
  (numba, no BLAS) or the NumPy expressions of `boards` give the scores; both reproduce the pinned boards of
  levels 0-8. `fragile_seam_ends` counts port choices that a score change of 2e-15 could move (zero so far,
  so platform differences in the last bits do not change the board).

Output per cell c and triangle edge j (j = 0: vertices 0-1, 1: 1-2, 2: 2-0): `nbr[c, j]` (int32), `nslot[c, j]`
(the neighbour's edge, uint8), `port[c, j]` (uint8) and `centres[c]` (float32). `pairs` lists the external seams
in RER Carrier order without sorting. `tests/test_bigboard.py` compares levels 0-8 with `boards.compose`.
"""
from __future__ import annotations

import hashlib
import json
import os
import resource
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import numpy as np

from . import boards

DIRECTIONS = boards._clean(boards.BASE_VERTICES)
DEFAULT = boards.CACHE / "big"
CHUNK = 1 << 20
FRAGILE_EPS = 2e-15   # score perturbation used to flag port choices that a last-bit difference could change


def _rows(n, chunk):
    for a in range(0, n, chunk):
        yield a, min(n, a + chunk)


def _map(fn, n, chunk, workers):
    """fn(a, b) on every row chunk; NumPy releases the GIL, so threads share the work. Results in order."""
    ranges = list(_rows(n, chunk))
    if workers <= 1 or len(ranges) == 1:
        return [fn(a, b) for a, b in ranges]
    with ThreadPoolExecutor(workers) as pool:
        return list(pool.map(lambda r: fn(*r), ranges))


def peak_rss() -> int:
    r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    return int(r if sys.platform == "darwin" else r * 1024)


# ------------------------------------------------------------------ tower
def _level0():
    raw = boards.BASE_VERTICES / np.linalg.norm(boards.BASE_VERTICES, axis=1, keepdims=True)
    f = boards._orient(raw, boards.BASE_FACES)
    v = boards._clean(boards._clean(raw))
    f = boards._orient(v, f).astype(np.int32)
    where = {(int(f[c, j]), int(f[c, (j + 1) % 3])): (c, j) for c in range(len(f)) for j in range(3)}
    nbr = np.empty((len(f), 3), np.int32)
    nslot = np.empty((len(f), 3), np.uint8)
    for c in range(len(f)):
        for j in range(3):
            nbr[c, j], nslot[c, j] = where[(int(f[c, (j + 1) % 3]), int(f[c, j]))]
    return v, f, nbr, nslot


def _clean_twice(v, chunk, workers=1):
    def run(a, b):
        v[a:b] = boards._clean(boards._clean(v[a:b]))
    _map(run, len(v), chunk, workers)


def _check_outward(v, f, chunk, workers=1):
    """`boards._orient` would flip no face (children of outward faces are outward)."""
    def run(a, b):
        x, y, z = v[f[a:b, 0]], v[f[a:b, 1]], v[f[a:b, 2]]
        return bool(np.any(np.einsum("ij,ij->i", np.cross(y - x, z - x), x + y + z) < 0.0))
    if any(_map(run, len(f), chunk, workers)):
        raise AssertionError("a face lost its outward orientation")


def _refine(v, f, nbr, nslot, chunk, workers=1):
    n_faces, n0 = len(f), len(v)

    def owned(a, b):
        return nbr[a:b] > np.arange(a, b, dtype=np.int32)[:, None]

    # midpoint numbers in order of first use: the owner of an edge is its face with the smaller index
    counts = _map(lambda a, b: int(owned(a, b).sum()), n_faces, chunk, workers)
    starts = n0 + np.concatenate([[0], np.cumsum(counts)[:-1]]).astype(np.int64)
    nxt = n0 + int(sum(counts))
    if nxt >= 2 ** 31:
        raise OverflowError("vertex numbers exceed int32")
    mid = np.empty((n_faces, 3), np.int32)
    ranges = list(_rows(n_faces, chunk))

    def number(i):
        a, b = ranges[i]
        own = owned(a, b)
        rank = np.cumsum(own.ravel(), dtype=np.int64).reshape(-1, 3) - 1 + starts[i]
        mid[a:b] = np.where(own, rank, -1)

    def borrow(a, b):
        m = mid[a:b]
        lost = m < 0
        m[lost] = mid[nbr[a:b][lost], nslot[a:b][lost]]

    _map(lambda a, b: number(a // chunk), n_faces, chunk, workers)
    _map(borrow, n_faces, chunk, workers)
    v2 = np.empty((nxt, 3))
    v2[:n0] = v

    def midpoints(a, b):
        fa = f[a:b]
        own = owned(a, b)
        u, w = fa[own], fa[:, (1, 2, 0)][own]
        lo, hi = np.minimum(u, w), np.maximum(u, w)
        points = v[lo] + v[hi]
        points /= np.sqrt(np.einsum("ij,ij->i", points, points))[:, None]
        v2[mid[a:b][own]] = points

    _map(midpoints, n_faces, chunk, workers)
    del v
    f2 = np.empty((4 * n_faces, 3), np.int32)
    nbr2 = np.empty((4 * n_faces, 3), np.int32)
    ns2 = np.empty((4 * n_faces, 3), np.uint8)

    def children(a, b):
        fa, m = f[a:b], mid[a:b]
        A, B, C = fa[:, 0], fa[:, 1], fa[:, 2]
        ab, bc, ca = m[:, 0], m[:, 1], m[:, 2]
        ch = f2[4 * a:4 * b].reshape(-1, 4, 3)
        ch[:, 0] = np.stack([A, ab, ca], 1)
        ch[:, 1] = np.stack([B, bc, ab], 1)
        ch[:, 2] = np.stack([C, ca, bc], 1)
        ch[:, 3] = np.stack([ab, bc, ca], 1)
        base = 4 * np.arange(a, b, dtype=np.int32)
        nb = nbr2[4 * a:4 * b].reshape(-1, 4, 3)
        ns = ns2[4 * a:4 * b].reshape(-1, 4, 3)
        # inner edges: child i (i < 3) edge 1 meets the middle child
        for i, k in ((0, 2), (1, 0), (2, 1)):
            nb[:, i, 1], ns[:, i, 1] = base + 3, k
            nb[:, 3, k], ns[:, 3, k] = base + i, 1
        # halves of parent edge j: (v_j, m) in child j edge 0, (m, v_j+1) in child j+1 edge 2
        g, k = nbr[a:b], nslot[a:b].astype(np.int32)
        for j in range(3):
            nb[:, j, 0], ns[:, j, 0] = 4 * g[:, j] + (k[:, j] + 1) % 3, 2
            nb[:, (j + 1) % 3, 2], ns[:, (j + 1) % 3, 2] = 4 * g[:, j] + k[:, j], 0

    _map(children, n_faces, chunk, workers)
    return v2, f2, nbr2, ns2


def tower(level: int, chunk: int = CHUNK, workers: int = 1):
    """Vertices, outward faces, neighbours and neighbour slots of the level-L geodesic tower."""
    v, f, nbr, nslot = _level0()
    for _ in range(level):
        v, f, nbr, nslot = _refine(v, f, nbr, nslot, chunk, workers)
        _clean_twice(v, chunk, workers)
        _check_outward(v, f, chunk, workers)
    return v, f, nbr, nslot


# ------------------------------------------------------------------ ports
def _scores(points, nbr, a, b):
    """float64 scores of the 12 port directions for the three seams of cells a..b (rows c*3 + j)."""
    node = points[a:b]
    frames = np.repeat(boards._frames(node), 3, axis=0)
    vec = points[nbr[a:b].ravel()] - np.repeat(node, 3, axis=0)
    vec /= np.maximum(np.linalg.norm(vec, axis=1, keepdims=True), 1e-15)
    return np.einsum("ni,nij->nj", vec, frames, optimize=True) @ DIRECTIONS.T


def _fragile(s64, s32, best):
    """Rows whose argmax could change if every float64 score moved by up to FRAGILE_EPS."""
    lo = (s64 - FRAGILE_EPS).astype(np.float32)
    hi = (s64 + FRAGILE_EPS).astype(np.float32)
    rows = np.arange(len(s64))
    top = lo[rows, best][:, None]
    hi[rows, best] = -np.inf
    j = np.arange(12)[None]
    return int(np.count_nonzero(np.any((hi > top) | ((hi == top) & (j < best[:, None])), axis=1)))


try:
    import numba
except ImportError:  # the NumPy path below gives the same board
    numba = None

if numba is not None:
    @numba.njit(parallel=True, cache=True)
    def _ports_kernel(points, nbr, directions, eps, port, fragile):
        """Per seam end: the cell's tangent frame, the unit vector to the neighbour, twelve float32 scores,
        the first maximum, and whether a score change of up to eps could move that maximum. IEEE operations
        in a fixed order (no BLAS, no contraction), so every platform computes the same bits."""
        for c in numba.prange(points.shape[0]):
            n0, n1, n2 = points[c, 0], points[c, 1], points[c, 2]
            r = max(np.sqrt(n0 * n0 + n1 * n1 + n2 * n2), 1e-15)
            n0, n1, n2 = n0 / r, n1 / r, n2 / r
            if abs(n2) > 0.9:
                f0, f1, f2 = 1.0, 0.0, 0.0
            else:
                f0, f1, f2 = 0.0, 0.0, 1.0
            t0, t1, t2 = f1 * n2 - f2 * n1, f2 * n0 - f0 * n2, f0 * n1 - f1 * n0
            r = max(np.sqrt(t0 * t0 + t1 * t1 + t2 * t2), 1e-15)
            t0, t1, t2 = t0 / r, t1 / r, t2 / r
            y0, y1, y2 = n1 * t2 - n2 * t1, n2 * t0 - n0 * t2, n0 * t1 - n1 * t0
            for j in range(3):
                g = nbr[c, j]
                w0, w1, w2 = points[g, 0] - points[c, 0], points[g, 1] - points[c, 1], points[g, 2] - points[c, 2]
                r = max(np.sqrt(w0 * w0 + w1 * w1 + w2 * w2), 1e-15)
                w0, w1, w2 = w0 / r, w1 / r, w2 / r
                ex = w0 * t0 + w1 * t1 + w2 * t2
                ey = w0 * y0 + w1 * y1 + w2 * y2
                ez = w0 * n0 + w1 * n1 + w2 * n2
                best = 0
                top = np.float32(-np.inf)
                s = np.empty(12)
                for k in range(12):
                    s[k] = ex * directions[k, 0] + ey * directions[k, 1] + ez * directions[k, 2]
                    v32 = np.float32(s[k])
                    if v32 > top:
                        top, best = v32, k
                port[c, j] = best
                low = np.float32(s[best] - eps)
                flag = False
                for k in range(12):
                    if k != best:
                        high = np.float32(s[k] + eps)
                        if high > low or (high == low and k < best):
                            flag = True
                fragile[c, j] = flag


def _assign(scores, keys):
    """The repair of `boards.compose` for one cell: its seams in edge-key order, one assignment."""
    from scipy.optimize import linear_sum_assignment
    ids = np.argsort(keys, kind="stable")
    rows, cols = linear_sum_assignment(-scores[ids])
    out = np.empty(3, np.uint8)
    out[ids[rows]] = cols
    return out


def ports(v, f, nbr, chunk=CHUNK, workers=1, kernel=None):
    """Cell centres (float64) and the port of every seam end, with clash and fragility counts.

    kernel=None uses the compiled kernel when numba is available, else the NumPy expressions of
    `boards.compose`; both are tested against the pinned boards."""
    if kernel is None:
        kernel = numba is not None
    cells = len(f)
    nv = np.int64(len(v))
    points = np.empty((cells, 3))

    def centres(a, b):
        p = v[f[a:b]].sum(axis=1)
        p /= np.linalg.norm(p, axis=1, keepdims=True)
        points[a:b] = p

    _map(centres, cells, chunk, workers)
    port = np.empty((cells, 3), np.uint8)
    if kernel:
        flags = np.empty((cells, 3), np.bool_)
        _ports_kernel(points, nbr, DIRECTIONS, FRAGILE_EPS, port, flags)
        fragile = int(np.count_nonzero(flags))
        del flags
        clashes = 0
        for a, b in _rows(cells, chunk):
            p = port[a:b]
            bad = np.flatnonzero((p[:, 0] == p[:, 1]) | (p[:, 1] == p[:, 2]) | (p[:, 0] == p[:, 2]))
            if bad.size:
                fa = f[a:b][bad].astype(np.int64)
                u, w = fa, fa[:, (1, 2, 0)]
                keys = np.minimum(u, w) * nv + np.maximum(u, w)
                for i, c in enumerate(bad):
                    sc = np.asarray(_scores(points, nbr, a + c, a + c + 1), dtype=np.float32)
                    p[c] = _assign(sc, keys[i])
            clashes += int(bad.size)
        return points, port, clashes, fragile

    def choose(a, b):
        s64 = _scores(points, nbr, a, b)
        sc = np.asarray(s64, dtype=np.float32)
        best = np.argmax(sc, axis=1)
        fragile = _fragile(s64, sc, best)
        del s64
        p = best.reshape(-1, 3).astype(np.uint8)
        bad = np.flatnonzero((p[:, 0] == p[:, 1]) | (p[:, 1] == p[:, 2]) | (p[:, 0] == p[:, 2]))
        if bad.size:
            fa = f[a:b][bad].astype(np.int64)
            u, w = fa, fa[:, (1, 2, 0)]
            keys = np.minimum(u, w) * nv + np.maximum(u, w)
            s3 = sc.reshape(-1, 3, 12)[bad]
            for i in range(len(bad)):
                p[bad[i]] = _assign(s3[i], keys[i])
        port[a:b] = p
        return int(bad.size), fragile

    counts = _map(choose, cells, chunk, workers)
    return points, port, sum(c for c, _ in counts), sum(x for _, x in counts)


def compose(level: int, chunk: int = CHUNK, keep64: bool = False, workers: int = 1, kernel=None) -> dict:
    started = time.time()
    v, f, nbr, nslot = tower(level, chunk, workers)
    points, port, clashes, fragile = ports(v, f, nbr, chunk, workers, kernel)
    del v, f
    board = {"level": level, "cells": len(nbr), "nbr": nbr, "nslot": nslot, "port": port,
             "centres": points.astype(np.float32), "clash_cells": clashes, "fragile_seam_ends": fragile}
    if keep64:
        board["centres64"] = points
    board["seconds"] = round(time.time() - started, 2)
    return board


# ------------------------------------------------------------------ seams in Carrier order
def _nslot(board):
    if "nslot" in board:
        return board["nslot"]
    nbr = board["nbr"]
    c = np.arange(len(nbr), dtype=np.int32)
    return np.stack([np.argmax(nbr[nbr[:, j]] == c[:, None], axis=1) for j in range(3)], 1).astype(np.uint8)


def iter_pairs(board, chunk=CHUNK, cells_only=False):
    """External seams in RER Carrier order, chunk by chunk: (low port id, high port id) int64, or cell ids."""
    nbr, port = board["nbr"], board["port"]
    nslot = _nslot(board)
    for a, b in _rows(len(nbr), chunk):
        c = np.arange(a, b, dtype=np.int64)[:, None]
        g = nbr[a:b].astype(np.int64)
        own = g > c
        p = port[a:b].astype(np.int64)
        order = np.argsort(np.where(own, p, 99), axis=1, kind="stable")
        take = lambda x: np.take_along_axis(x, order, axis=1)
        keep = take(own)
        gs = take(g)
        if cells_only:
            yield np.broadcast_to(c, gs.shape)[keep].astype(np.int32), gs[keep].astype(np.int32)
        else:
            q = port[nbr[a:b], nslot[a:b]].astype(np.int64)
            yield (12 * c + take(p))[keep], (12 * gs + take(q))[keep]


def pairs(board, chunk=CHUNK):
    parts = list(iter_pairs(board, chunk))
    return np.concatenate([x for x, _ in parts]), np.concatenate([y for _, y in parts])


def cell_pairs(board, chunk=CHUNK):
    parts = list(iter_pairs(board, chunk, cells_only=True))
    return np.concatenate([x for x, _ in parts]), np.concatenate([y for _, y in parts])


def external_sha256(board, chunk=CHUNK) -> str:
    h = hashlib.sha256()
    for a, b in iter_pairs(board, chunk):
        h.update(np.stack([a, b], 1).astype("<i8").tobytes())
    return h.hexdigest()


def structure(board, chunk=CHUNK) -> dict:
    nbr, port = board["nbr"], board["port"]
    nslot = _nslot(board)
    cells, seams, distinct, matching, gateways = len(nbr), 0, True, True, True
    for a, b in _rows(cells, chunk):
        c = np.arange(a, b, dtype=np.int32)[:, None]
        g, p = nbr[a:b], port[a:b]
        seams += int((g > c).sum())
        distinct &= bool(np.all(g != c))
        back = nbr[g, nslot[a:b]] == c
        three = (p[:, 0] != p[:, 1]) & (p[:, 1] != p[:, 2]) & (p[:, 0] != p[:, 2]) & np.all(p < 12, axis=1)
        matching &= bool(np.all(back) and np.all(three))
        gateways &= bool(np.all(three))
    return {"cells": cells, "cells_are_20_4^L": cells == 20 * 4 ** board["level"], "external_seams": seams,
            "external_is_3N/2": seams == 3 * cells // 2, "ends_in_distinct_cells": distinct,
            "external_ports_form_a_matching": matching, "three_gateways_per_cell": gateways}


def to_external(board) -> np.ndarray:
    """(seams, 2) int64 in Carrier order: the `external` array of `boards` (small levels only)."""
    a, b = pairs(board)
    return np.stack([a, b], 1)


# ------------------------------------------------------------------ files
def save(board, folder=None) -> Path:
    folder = Path(folder or DEFAULT / f"L{board['level']}")
    folder.mkdir(parents=True, exist_ok=True)
    for name in ("nbr", "nslot", "port", "centres"):
        np.save(folder / f"{name}.npy", board[name])
    meta = {"level": board["level"], "cells": int(board["cells"]), "external_sha256": external_sha256(board),
            "structure": structure(board), "clash_cells": board.get("clash_cells"),
            "fragile_seam_ends": board.get("fragile_seam_ends"), "fragile_eps": FRAGILE_EPS,
            "seconds": board.get("seconds"), "peak_rss_bytes": peak_rss()}
    (folder / "board.json").write_text(json.dumps(meta, indent=1) + "\n")
    return folder


def load(level_or_folder, mmap: bool = True) -> dict:
    folder = Path(level_or_folder) if not isinstance(level_or_folder, int) else DEFAULT / f"L{level_or_folder}"
    meta = json.loads((folder / "board.json").read_text())
    mode = "r" if mmap else None
    board = {"level": meta["level"], "cells": meta["cells"], "meta": meta}
    for name in ("nbr", "nslot", "port", "centres"):
        if (folder / f"{name}.npy").exists():
            board[name] = np.load(folder / f"{name}.npy", mmap_mode=mode)
    return board


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(description="compose and save a federation level")
    ap.add_argument("level", type=int)
    ap.add_argument("--out")
    ap.add_argument("--chunk", type=int, default=CHUNK)
    ap.add_argument("--workers", type=int, default=min(32, os.cpu_count() or 1))
    o = ap.parse_args()
    b = compose(o.level, o.chunk, workers=o.workers)
    t = time.time()
    folder = save(b, o.out)
    print(json.dumps({"folder": str(folder), "compose_seconds": b["seconds"], "save_seconds": round(time.time() - t, 1),
                      "clash_cells": b["clash_cells"], "fragile_seam_ends": b["fragile_seam_ends"],
                      "peak_rss_gb": round(peak_rss() / 2 ** 30, 2)}))
