"""Spherical federations of echosahedra at any refinement level, checked against RER.

RER fixes one cell (the echosahedron: 12 ports, 30 seams, 20 faces with the icosahedron's incidence) and ships
the federations of 20, 80 and 320 cells. Its reader for larger boards accepts deposited refinements whose every
cell is complete and whose external seams match three distinct ports of each cell; at levels 0-2 it requires
seam-for-seam equality with the shipped boards. This module composes the same boards at any level:

* the geodesic tower: the icosahedron's 20 triangles, each split into four per level (edge midpoints pushed to
  the unit sphere, faces oriented outward);
* one complete echosahedron on every triangle (20 * 4^L cells);
* one external seam between every pair of triangles that share an edge; at each end it uses the cell's port whose
  direction (in the cell's tangent frame) points closest to the neighbour, an exact assignment repairing ties.

`check(level)` compares the result with RER's shipped boards (levels 0-2) and applies RER's structural tests.
"""
from __future__ import annotations

import hashlib
from pathlib import Path

import numpy as np

PHI = (1.0 + 5.0 ** 0.5) / 2.0
BASE_VERTICES = np.array([(-1, PHI, 0), (1, PHI, 0), (-1, -PHI, 0), (1, -PHI, 0), (0, -1, PHI), (0, 1, PHI),
                          (0, -1, -PHI), (0, 1, -PHI), (PHI, 0, -1), (PHI, 0, 1), (-PHI, 0, -1), (-PHI, 0, 1)], float)
BASE_FACES = np.array([(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2),
                       (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5),
                       (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)], np.int64)
CACHE = Path(__file__).resolve().parents[1] / "runs" / "boards"


def _clean(v):
    v = np.asarray(v, float).copy()
    v /= np.linalg.norm(v, axis=1, keepdims=True)
    v[np.abs(v) < 5.0e-16] = 0.0
    return v


def _orient(v, f):
    f = f.copy()
    a, b, c = v[f[:, 0]], v[f[:, 1]], v[f[:, 2]]
    flip = np.einsum("ij,ij->i", np.cross(b - a, c - a), a + b + c) < 0.0
    f[flip, 1], f[flip, 2] = f[flip, 2].copy(), f[flip, 1].copy()
    return f


def _refine(v, f):
    """Split every triangle into four; midpoints are numbered in order of first use."""
    n0 = len(v)
    ab, bc, ca = f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]
    # first-use order of the three midpoints per face: ab, bc, ca
    edges = np.stack([ab, bc, ca], axis=1).reshape(-1, 2)
    keys = np.minimum(edges[:, 0], edges[:, 1]) * n0 + np.maximum(edges[:, 0], edges[:, 1])
    uniq, first, inverse = np.unique(keys, return_index=True, return_inverse=True)
    rank = np.empty(len(uniq), np.int64)
    rank[np.argsort(first, kind="stable")] = np.arange(len(uniq))
    mid = n0 + rank[inverse].reshape(-1, 3)
    lo, hi = uniq // n0, uniq % n0
    points = v[lo] + v[hi]
    points /= np.sqrt(np.einsum("ij,ij->i", points, points))[:, None]
    new = np.empty((len(uniq), 3))
    new[rank] = points
    vertices = np.vstack([v, new])
    m_ab, m_bc, m_ca = mid[:, 0], mid[:, 1], mid[:, 2]
    a, b, c = f[:, 0], f[:, 1], f[:, 2]
    children = np.stack([np.stack([a, m_ab, m_ca], 1), np.stack([b, m_bc, m_ab], 1),
                         np.stack([c, m_ca, m_bc], 1), np.stack([m_ab, m_bc, m_ca], 1)], axis=1).reshape(-1, 3)
    return vertices, children


def tower(level: int):
    """Vertices and outward faces of the geodesic tower (each level normalises twice, as the deposited boards)."""
    raw = BASE_VERTICES / np.linalg.norm(BASE_VERTICES, axis=1, keepdims=True)
    f = _orient(raw, BASE_FACES)
    v = _clean(_clean(raw))
    f = _orient(v, f)
    for _ in range(level):
        v, f = _refine(v, f)
        v = _clean(_clean(v))
        f = _orient(v, f)
    return v, f


def _frames(points):
    n = points / np.maximum(np.linalg.norm(points, axis=1, keepdims=True), 1e-15)
    ref = np.tile([0.0, 0.0, 1.0], (len(n), 1))
    ref[np.abs(n[:, 2]) > 0.9] = [1.0, 0.0, 0.0]
    tx = np.cross(ref, n)
    tx /= np.maximum(np.linalg.norm(tx, axis=1, keepdims=True), 1e-15)
    ty = np.cross(n, tx)
    return np.stack((tx, ty, n), axis=2)


def compose(level: int) -> dict:
    """External seams and cell centres of the level-L board."""
    from scipy.optimize import linear_sum_assignment

    v, f = tower(level)
    cells = len(f)
    points = v[f].sum(axis=1)
    points /= np.linalg.norm(points, axis=1, keepdims=True)
    e = np.concatenate([f[:, (0, 1)], f[:, (1, 2)], f[:, (2, 0)]])
    keys = np.minimum(e[:, 0], e[:, 1]) * len(v) + np.maximum(e[:, 0], e[:, 1])
    face = np.tile(np.arange(cells), 3)
    order = np.argsort(keys, kind="stable")
    k, fs = keys[order], face[order]
    if len(k) % 2 or not np.array_equal(k[0::2], k[1::2]):
        raise AssertionError("every mesh edge must border exactly two cells")
    left, right = np.minimum(fs[0::2], fs[1::2]), np.maximum(fs[0::2], fs[1::2])
    node = np.empty(2 * len(left), np.int64)
    other = np.empty_like(node)
    node[0::2], node[1::2] = left, right
    other[0::2], other[1::2] = right, left
    directions = _clean(BASE_VERTICES)
    frames = _frames(points)
    vec = points[other] - points[node]
    vec /= np.maximum(np.linalg.norm(vec, axis=1, keepdims=True), 1e-15)
    scores = np.asarray(np.einsum("ni,nij->nj", vec, frames[node], optimize=True) @ directions.T, dtype=np.float32)
    port = np.argmax(scores, axis=1).astype(np.int64)
    slot = node * 12 + port
    _, first, count = np.unique(slot, return_index=True, return_counts=True)
    clash = np.unique(slot[first[count > 1]] // 12)
    if clash.size:
        by = np.argsort(node, kind="stable")
        sn = node[by]
        for c in clash:
            ids = by[np.searchsorted(sn, c, "left"):np.searchsorted(sn, c, "right")]
            rows, cols = linear_sum_assignment(-scores[ids])
            port[ids[rows]] = cols
    a, b = left * 12 + port[0::2], right * 12 + port[1::2]
    external = np.stack([a, b], axis=1).astype(np.int64)
    if np.unique(external).size != external.size:
        raise AssertionError("a port is glued twice")
    return {"level": level, "cells": cells, "external": external, "centres": points}


def load(level: int) -> dict:
    """Composed board, cached under runs/boards."""
    path = CACHE / f"L{level}.npz"
    if path.exists():
        with np.load(path) as z:
            return {"level": level, "cells": int(z["cells"]), "external": z["external"], "centres": z["centres"]}
    board = compose(level)
    CACHE.mkdir(parents=True, exist_ok=True)
    np.savez_compressed(path, cells=board["cells"], external=board["external"], centres=board["centres"])
    return board


def external_sha256(external) -> str:
    e = np.sort(np.asarray(external, np.int64), axis=1)
    e = e[np.lexsort((e[:, 1], e[:, 0]))]
    return hashlib.sha256(e.astype("<i8").tobytes()).hexdigest()


def structure(board: dict) -> dict:
    """RER's tests of a supplied refinement, vectorised: complete cells, a matching, three gateways per cell."""
    ext, cells = board["external"], board["cells"]
    owners = ext // 12
    per_cell = np.bincount(owners.ravel(), minlength=cells)
    return {"cells": cells, "cells_are_20_4^L": cells == 20 * 4 ** board["level"],
            "external_seams": len(ext), "external_is_3N/2": len(ext) == 3 * cells // 2,
            "ends_in_distinct_cells": bool(np.all(owners[:, 0] != owners[:, 1])),
            "external_ports_form_a_matching": bool(np.unique(ext).size == ext.size),
            "three_gateways_per_cell": bool(np.all(per_cell == 3))}


def carrier(board: dict):
    """RER's Carrier object on a composed board (every cell keeps RER's 30 seams)."""
    from . import rer
    rer.root()
    from model.executable_model.carrier import CELL_SEAMS, Carrier
    cells = board["cells"]
    template = np.asarray(CELL_SEAMS, np.int64)
    inside = (12 * np.arange(cells)[:, None, None] + template[None]).reshape(-1, 2)
    seams = np.concatenate([inside, board["external"]])
    return Carrier(f"{cells} cells", 12 * cells, seams.tolist())
