from __future__ import annotations

from copy import deepcopy
import json
import math
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEMO_PATH = ROOT / "app" / "demo_models" / "demo_04.json"
BRACING_LAYERS = {"CVH", "CVV"}
CONNECTIONS = (
    # pillar, lower connection node, lower chord, upper chord, pillar top node
    (2075, 1011, 1791, 1821, 996),
    (2076, 1010, 1864, 1894, 998),
    (2079, 1014, 25, 55, 1003),
    (2080, 1015, 100, 130, 1005),
)
BRACE_ENDPOINT_CONNECTIONS = (
    # brace endpoint node, crossed pillar, crossed lower chord
    (1013, 2078, 32),
    (1016, 2081, 107),
)
ADDITIONAL_LOWER_CONNECTIONS = (
    (1012, 2074, 1798),
    (1009, 2077, 1871),
)
ADDITIONAL_TOP_CONNECTIONS = (
    # pillar top node, crossed upper chord
    (994, 1814),
    (1000, 1887),
    (1001, 48),
    (1007, 123),
)
TOLERANCE = 1.0e-8


def segment_parameter(point: dict, start: dict, end: dict) -> float:
    direction = tuple(float(end[axis]) - float(start[axis]) for axis in "xyz")
    relative = tuple(float(point[axis]) - float(start[axis]) for axis in "xyz")
    length_squared = sum(value * value for value in direction)
    if length_squared <= TOLERANCE * TOLERANCE:
        raise ValueError("Barra de comprimento nulo durante a reparacao.")
    parameter = sum(a * b for a, b in zip(relative, direction)) / length_squared
    closest = tuple(float(start[axis]) + parameter * direction[index] for index, axis in enumerate("xyz"))
    distance = math.sqrt(sum((float(point[axis]) - closest[index]) ** 2 for index, axis in enumerate("xyz")))
    if not TOLERANCE < parameter < 1.0 - TOLERANCE or distance > TOLERANCE:
        raise ValueError(
            f"No #{point['id']} nao esta no interior exato da barra; t={parameter}, distancia={distance}."
        )
    return parameter


def project_node_to_element(node: dict, element: dict, node_by_id: dict[int, dict]) -> float:
    start = node_by_id[element["start_node"]]
    end = node_by_id[element["end_node"]]
    direction = tuple(float(end[axis]) - float(start[axis]) for axis in "xyz")
    horizontal_axis = max((0, 1), key=lambda index: abs(direction[index]))
    if abs(direction[horizontal_axis]) <= TOLERANCE:
        raise ValueError(f"Barra #{element['id']} sem direcao horizontal para o ajuste do pilar.")
    axis = "xyz"[horizontal_axis]
    parameter = (
        float(node[axis]) - float(start[axis])
    ) / direction[horizontal_axis]
    if not 0.0 < parameter < 1.0:
        raise ValueError(f"Projecao do no #{node['id']} caiu fora da barra #{element['id']}.")
    for index, axis in enumerate("xyz"):
        node[axis] = float(start[axis]) + parameter * direction[index]
    return parameter


def split_element(
    elements: list[dict],
    element_by_id: dict[int, dict],
    node_by_id: dict[int, dict],
    element_id: int,
    node_id: int,
    next_element_id: int,
) -> int:
    element = element_by_id[element_id]
    node = node_by_id[node_id]
    segment_parameter(
        node,
        node_by_id[element["start_node"]],
        node_by_id[element["end_node"]],
    )
    original_end_node = element["end_node"]
    second = deepcopy(element)
    second["id"] = next_element_id
    second["start_node"] = node_id
    second["end_node"] = original_end_node
    element["end_node"] = node_id

    axial_member = bool(element.get("tension_only")) or all(
        bool(element.get(key))
        for key in (
            "start_release_ry",
            "start_release_rz",
            "end_release_ry",
            "end_release_rz",
        )
    )
    for axis in ("rx", "ry", "rz"):
        value = axial_member and axis != "rx"
        element[f"end_release_{axis}"] = value
        second[f"start_release_{axis}"] = value

    elements.append(second)
    element_by_id[second["id"]] = second
    return next_element_id + 1


def connected_components(nodes: list[dict], elements: list[dict]) -> tuple[list[list[int]], list[int]]:
    adjacency = {node["id"]: set() for node in nodes}
    for element in elements:
        adjacency[element["start_node"]].add(element["end_node"])
        adjacency[element["end_node"]].add(element["start_node"])
    orphan_ids = sorted(node_id for node_id, neighbors in adjacency.items() if not neighbors)
    visited: set[int] = set()
    components: list[list[int]] = []
    for first in adjacency:
        if first in visited:
            continue
        pending = [first]
        visited.add(first)
        component: list[int] = []
        while pending:
            current = pending.pop()
            component.append(current)
            for neighbor in adjacency[current]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    pending.append(neighbor)
        components.append(component)
    return components, orphan_ids


def repair() -> None:
    document = json.loads(DEMO_PATH.read_text(encoding="utf-8"))
    nodes = document["nodes"]
    elements = document["elements"]
    node_by_id = {node["id"]: node for node in nodes}
    element_by_id = {element["id"]: element for element in elements}
    section_by_id = {section["id"]: section for section in document.get("sections", [])}
    if len(nodes) != 1324 or len(elements) not in (2541, 2553, 2557, 2565):
        raise ValueError("O Demo 4 nao corresponde a versao auditada para esta reparacao.")

    first_stage_repaired = len(elements) >= 2553
    second_stage_repaired = len(elements) >= 2557
    third_stage_repaired = len(elements) >= 2565
    if not first_stage_repaired:
        affected_element_ids = {
            element_id
            for pillar_id, _, lower_id, upper_id, _ in CONNECTIONS
            for element_id in (pillar_id, lower_id, upper_id)
        }
        if any(
            load.get("element_id") in affected_element_ids
            for key in ("member_point_loads", "member_distributed_loads")
            for load in document.get(key, [])
        ):
            raise ValueError("Uma barra a dividir recebeu carga direta depois da auditoria.")
        if any(
            affected_element_ids.intersection(group.get("element_ids") or [])
            for group in document.get("load_groups", [])
        ):
            raise ValueError("Uma barra a dividir entrou em grupo de carga depois da auditoria.")
        if any(
            affected_element_ids.intersection(panel.get("element_ids") or [])
            for panel in document.get("load_panels", [])
        ):
            raise ValueError("Uma barra a dividir entrou em pano de carga depois da auditoria.")

        next_element_id = max(element_by_id) + 1
        for pillar_id, lower_node_id, lower_chord_id, upper_chord_id, top_node_id in CONNECTIONS:
            top_node = node_by_id[top_node_id]
            upper_chord = element_by_id[upper_chord_id]
            project_node_to_element(top_node, upper_chord, node_by_id)
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                pillar_id,
                lower_node_id,
                next_element_id,
            )
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                lower_chord_id,
                lower_node_id,
                next_element_id,
            )
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                upper_chord_id,
                top_node_id,
                next_element_id,
            )

    if not second_stage_repaired:
        affected_element_ids = {
            element_id
            for _, pillar_id, lower_chord_id in BRACE_ENDPOINT_CONNECTIONS
            for element_id in (pillar_id, lower_chord_id)
        }
        if any(
            load.get("element_id") in affected_element_ids
            for key in ("member_point_loads", "member_distributed_loads")
            for load in document.get(key, [])
        ):
            raise ValueError("Uma ligacao de contraventamento recebeu carga direta depois da auditoria.")
        if any(
            affected_element_ids.intersection(group.get("element_ids") or [])
            for group in document.get("load_groups", [])
        ):
            raise ValueError("Uma ligacao de contraventamento entrou em grupo de carga depois da auditoria.")
        if any(
            affected_element_ids.intersection(panel.get("element_ids") or [])
            for panel in document.get("load_panels", [])
        ):
            raise ValueError("Uma ligacao de contraventamento entrou em pano de carga depois da auditoria.")
        next_element_id = max(element_by_id) + 1
        for node_id, pillar_id, lower_chord_id in BRACE_ENDPOINT_CONNECTIONS:
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                pillar_id,
                node_id,
                next_element_id,
            )
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                lower_chord_id,
                node_id,
                next_element_id,
            )

    if not third_stage_repaired:
        affected_element_ids = {
            element_id
            for _, pillar_id, lower_chord_id in ADDITIONAL_LOWER_CONNECTIONS
            for element_id in (pillar_id, lower_chord_id)
        } | {upper_chord_id for _, upper_chord_id in ADDITIONAL_TOP_CONNECTIONS}
        if any(
            load.get("element_id") in affected_element_ids
            for key in ("member_point_loads", "member_distributed_loads")
            for load in document.get(key, [])
        ):
            raise ValueError("Uma ligacao complementar recebeu carga direta depois da auditoria.")
        if any(
            affected_element_ids.intersection(group.get("element_ids") or [])
            for group in document.get("load_groups", [])
        ):
            raise ValueError("Uma ligacao complementar entrou em grupo de carga depois da auditoria.")
        if any(
            affected_element_ids.intersection(panel.get("element_ids") or [])
            for panel in document.get("load_panels", [])
        ):
            raise ValueError("Uma ligacao complementar entrou em pano de carga depois da auditoria.")
        next_element_id = max(element_by_id) + 1
        for node_id, pillar_id, lower_chord_id in ADDITIONAL_LOWER_CONNECTIONS:
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                pillar_id,
                node_id,
                next_element_id,
            )
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                lower_chord_id,
                node_id,
                next_element_id,
            )
        for top_node_id, upper_chord_id in ADDITIONAL_TOP_CONNECTIONS:
            top_node = node_by_id[top_node_id]
            upper_chord = element_by_id[upper_chord_id]
            project_node_to_element(top_node, upper_chord, node_by_id)
            next_element_id = split_element(
                elements,
                element_by_id,
                node_by_id,
                upper_chord_id,
                top_node_id,
                next_element_id,
            )

    bracing_count = 0
    for element in elements:
        if BRACING_LAYERS.intersection(element.get("layers") or []):
            element["tension_only"] = True
            element["comp_only"] = False
            element["start_release_ry"] = True
            element["start_release_rz"] = True
            element["end_release_ry"] = True
            element["end_release_rz"] = True
            bracing_count += 1

    support_node_ids = {support["node_id"] for support in document["supports"]}
    column_ids: list[int] = []
    for element in elements:
        section = section_by_id.get(element.get("section_id"))
        if section and section.get("mass_kg_m") is not None:
            element["mass_kg_m"] = float(section["mass_kg_m"])

        if not ({element["start_node"], element["end_node"]} & support_node_ids):
            continue
        start = node_by_id[element["start_node"]]
        end = node_by_id[element["end_node"]]
        if (
            abs(float(start["x"]) - float(end["x"])) <= TOLERANCE
            and abs(float(start["y"]) - float(end["y"])) <= TOLERANCE
            and abs(float(start["z"]) - float(end["z"])) > 1.0
        ):
            element["rotation_deg"] = 90.0
            column_ids.append(element["id"])

    components, orphan_ids = connected_components(nodes, elements)
    if len(components) != 1 or orphan_ids:
        raise ValueError(
            f"Reparacao incompleta: {len(components)} componentes, nos orfaos {orphan_ids}."
        )
    if len(elements) != 2565 or bracing_count != 151:
        raise ValueError(
            f"Contagem final inesperada: {len(elements)} barras, {bracing_count} contraventamentos."
        )
    if len(column_ids) != 34:
        raise ValueError(f"Contagem inesperada de pilares orientados: {len(column_ids)}.")
    if len({element["id"] for element in elements}) != len(elements):
        raise ValueError("IDs de barras duplicados apos a reparacao.")

    document["description"] = (
        "Modelo espacial de um galpao 30 x 72 m, com 1.324 nos, 2.565 barras, "
        "34 apoios, contraventamentos somente a tracao e combinacoes de carga."
    )
    DEMO_PATH.write_text(
        json.dumps(document, ensure_ascii=True, indent=2) + "\n",
        encoding="utf-8",
    )
    print(
        "Demo 4 reparado: 1 componente, 0 nos orfaos, "
        f"{len(elements)} barras, {bracing_count} contraventamentos e "
        f"{len(column_ids)} pilares orientados."
    )


if __name__ == "__main__":
    repair()
