from __future__ import annotations

import json
from pathlib import Path
import sys

import numpy as np
from scipy.sparse import csc_matrix, lil_matrix
from scipy.sparse.linalg import eigsh

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from app.engines.opensees_engine import OpenSeesPyEngine


DOF_LABELS = ("UX", "UY", "UZ", "RX", "RY", "RZ")


def frame_local_stiffness(e, g, area, iy, iz, torsion, length):
    matrix = np.zeros((12, 12))

    def axial_pair(first, second, value):
        matrix[first, first] += value
        matrix[second, second] += value
        matrix[first, second] -= value
        matrix[second, first] -= value

    axial_pair(0, 6, e * area / length)
    axial_pair(3, 9, g * torsion / length)
    for indices, inertia, sign in (
        ((1, 5, 7, 11), iz, 1.0),
        ((2, 4, 8, 10), iy, -1.0),
    ):
        a = 12 * e * inertia / length**3
        b = sign * 6 * e * inertia / length**2
        c = 4 * e * inertia / length
        d = 2 * e * inertia / length
        block = np.array(
            ((a, b, -a, b), (b, c, -b, d), (-a, -b, a, -b), (b, d, -b, c))
        )
        for row, global_row in enumerate(indices):
            for column, global_column in enumerate(indices):
                matrix[global_row, global_column] += block[row, column]
    return matrix


def main() -> None:
    document = json.loads((ROOT / "app" / "demo_models" / "demo_04.json").read_text(encoding="utf-8"))
    nodes = document["nodes"]
    node_by_id = {node["id"]: node for node in nodes}
    node_position = {node["id"]: index for index, node in enumerate(nodes)}
    material_by_id = {material["id"]: material for material in document["materials"]}
    stiffness = lil_matrix((6 * len(nodes), 6 * len(nodes)), dtype=float)

    def assemble(element_matrix, dofs):
        for row, global_row in enumerate(dofs):
            for column, global_column in enumerate(dofs):
                value = element_matrix[row, column]
                if value:
                    stiffness[global_row, global_column] += value

    for element in document["elements"]:
        start = node_by_id[element["start_node"]]
        end = node_by_id[element["end_node"]]
        material = material_by_id[element["material_id"]]
        e = float(material["e"])
        g = float(material.get("g") or e / 2.6)
        frame = OpenSeesPyEngine._build_member_frame(
            tuple(float(start[axis]) for axis in "xyz"),
            tuple(float(end[axis]) for axis in "xyz"),
            float(element.get("rotation_deg") or 0),
        )
        x_axis, y_axis, z_axis, length = frame
        start_position = node_position[element["start_node"]]
        end_position = node_position[element["end_node"]]
        if element.get("tension_only"):
            direction = np.array(x_axis)
            block = e * float(element["area"]) / length * np.outer(direction, direction)
            element_matrix = np.block([[block, -block], [-block, block]])
            dofs = [6 * start_position + index for index in range(3)] + [
                6 * end_position + index for index in range(3)
            ]
        else:
            local = frame_local_stiffness(
                e,
                g,
                float(element["area"]),
                float(element["iy"]),
                float(element["iz"]),
                float(element["j"]),
                length,
            )
            rotation = np.array((x_axis, y_axis, z_axis))
            transformation = np.zeros((12, 12))
            for block_index in range(4):
                offset = 3 * block_index
                transformation[offset : offset + 3, offset : offset + 3] = rotation
            element_matrix = transformation.T @ local @ transformation
            dofs = [6 * start_position + index for index in range(6)] + [
                6 * end_position + index for index in range(6)
            ]
        assemble(element_matrix, dofs)

    fixed_dofs = set()
    for support in document["supports"]:
        position = node_position[support["node_id"]]
        for offset, key in enumerate(("ux", "uy", "uz", "rx", "ry", "rz")):
            raw = support.get(key)
            mode = raw.get("mode") if isinstance(raw, dict) else ("fixed" if raw else "free")
            if mode == "fixed":
                fixed_dofs.add(6 * position + offset)
            elif mode == "elastic":
                stiffness[6 * position + offset, 6 * position + offset] += float(raw["stiffness"])

    free_dofs = np.array([index for index in range(stiffness.shape[0]) if index not in fixed_dofs])
    free_stiffness = csc_matrix(stiffness[free_dofs, :][:, free_dofs])
    eigenvalues, eigenvectors = eigsh(
        free_stiffness,
        k=12,
        sigma=1.0,
        which="LM",
        tol=1e-8,
        maxiter=40_000,
    )
    for mode_index in np.argsort(np.abs(eigenvalues)):
        vector = eigenvectors[:, mode_index]
        print(f"\nAUTOVALOR {eigenvalues[mode_index]:.12g}")
        for vector_index in np.argsort(np.abs(vector))[-8:][::-1]:
            global_dof = int(free_dofs[vector_index])
            node = nodes[global_dof // 6]
            print(
                f"  no #{node['id']} {DOF_LABELS[global_dof % 6]}: "
                f"{vector[vector_index]:+.6g} em ({node['x']}, {node['y']}, {node['z']})"
            )


if __name__ == "__main__":
    main()
