from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Iterable, cast

from .engines.opensees_engine import DISTRIBUTED_LOAD_EQUIVALENT_SEGMENTS, EPS
from .model_scale import ModelScale, classify_model_scale
from .schemas import SolveRequest


CALCULATION_CLASSES: tuple[ModelScale, ...] = (
    "small",
    "professional",
    "large",
    "extreme",
)
CLASS_RANK = {name: index for index, name in enumerate(CALCULATION_CLASSES)}
CLASS_MEMORY_MB: dict[ModelScale, int] = {
    "small": 2_048,
    "professional": 8_192,
    "large": 32_768,
    "extreme": 65_536,
}
PANEL_LOAD_SEGMENT_ESTIMATE = 2
ANALYSIS_PASS_BATCH_SIZE = 8
DISTRIBUTED_LOAD_DISCONTINUITY_FACES = 2


@dataclass(frozen=True)
class CalculationRequirements:
    required_class: ModelScale
    node_count: int
    element_count: int
    estimated_dof: int
    load_item_count: int
    estimated_memory_mb: int


def class_rank(value: str) -> int:
    try:
        return CLASS_RANK[cast(ModelScale, value)]
    except KeyError as exc:
        raise ValueError(f"Classe de calculo desconhecida: {value}") from exc


def highest_class(classes: Iterable[ModelScale]) -> ModelScale:
    return max(classes, key=class_rank)


def classes_runnable_by(pool_class: ModelScale) -> tuple[ModelScale, ...]:
    return CALCULATION_CLASSES[: class_rank(pool_class) + 1]


def pool_can_run(pool_class: ModelScale, required_class: ModelScale) -> bool:
    return class_rank(pool_class) >= class_rank(required_class)


def estimate_panel_load_item_count(request: SolveRequest) -> int:
    elements = getattr(request, "elements", ()) or ()
    element_count = len(elements)
    total = 0
    for panel in getattr(request, "load_panels", ()) or ():
        panel_loads = getattr(panel, "loads", ()) or ()
        receiver_ids = getattr(panel, "element_ids", ()) or ()
        receiver_candidates = len(receiver_ids) or element_count
        for load in panel_loads:
            component_count = 3 if getattr(load, "direction", "normal") == "normal" else 1
            total += receiver_candidates * component_count * PANEL_LOAD_SEGMENT_ESTIMATE
    return total


def _element_lengths_by_id(request: SolveRequest) -> dict[int, float]:
    node_points: dict[int, tuple[float, float, float]] = {}
    for node in getattr(request, "nodes", ()) or ():
        try:
            node_points[int(node.id)] = (
                float(node.x),
                float(node.y),
                float(node.z),
            )
        except (AttributeError, TypeError, ValueError):
            continue

    lengths: dict[int, float] = {}
    for element in getattr(request, "elements", ()) or ():
        try:
            start = node_points[int(element.start_node)]
            end = node_points[int(element.end_node)]
            lengths[int(element.id)] = math.dist(start, end)
        except (AttributeError, KeyError, TypeError, ValueError):
            continue
    return lengths


def _distributed_load_item_count(load: object, length: float | None) -> int:
    """Estimate the dominant input, solver-load, or mandatory-station storage.

    A full-span uniform load remains one OpenSees ``beamUniform`` item. Every
    other nonzero shape is conservatively represented by point loads, and each
    equivalent point produces two diagram faces at its discontinuity. Invalid
    or incomplete geometry takes the conservative expanded path; validated
    ``SolveRequest`` instances never depend on that fallback.
    """

    expanded_count = (
        max(4, DISTRIBUTED_LOAD_EQUIVALENT_SEGMENTS)
        * DISTRIBUTED_LOAD_DISCONTINUITY_FACES
    )
    if length is None or not math.isfinite(length) or length <= EPS:
        return expanded_count

    try:
        x1 = float(getattr(load, "x1"))
        raw_x2 = getattr(load, "x2")
        x2 = length if raw_x2 is None else float(raw_x2)
        w1 = float(getattr(load, "w1"))
        w2 = float(getattr(load, "w2"))
    except (AttributeError, TypeError, ValueError):
        return expanded_count
    if not all(math.isfinite(value) for value in (x1, x2, w1, w2)):
        return expanded_count
    if x1 < -EPS or x2 < -EPS or x1 > length + EPS or x2 > length + EPS:
        return expanded_count

    x1 = min(max(x1, 0.0), length)
    x2 = min(max(x2, 0.0), length)
    if x2 <= x1 + EPS:
        return expanded_count
    if abs(w1) <= EPS and abs(w2) <= EPS:
        # The solver skips the force, but the validated request item still
        # occupies transport and parsing memory. Keep the former unit cost.
        return 1
    if (
        abs(x1) <= EPS
        and abs(x2 - length) <= EPS
        and abs(w1 - w2) <= EPS
    ):
        return 1
    return expanded_count


def estimate_member_distributed_load_item_count(request: SolveRequest) -> int:
    loads = getattr(request, "member_distributed_loads", ()) or ()
    if not loads:
        return 0
    length_by_element_id = _element_lengths_by_id(request)
    total = 0
    for load in loads:
        try:
            length = length_by_element_id.get(int(load.element_id))
        except (AttributeError, TypeError, ValueError):
            length = None
        total += _distributed_load_item_count(load, length)
    return total


def estimate_load_item_count(request: SolveRequest) -> int:
    return (
        len(getattr(request, "loads", ()) or ())
        + len(getattr(request, "member_point_loads", ()) or ())
        + estimate_member_distributed_load_item_count(request)
        + (
            sum(not element.tension_only for element in request.elements)
            if getattr(request, "include_self_weight", False)
            else 0
        )
        + estimate_panel_load_item_count(request)
    )


def estimate_analysis_pass_count(request: SolveRequest) -> int:
    settings = getattr(request, "project_analysis", None)
    if not settings or not settings.enabled:
        return 1
    combinations = [
        combination
        for combination in request.combinations
        if combination.enabled and combination.limit_state in settings.include_limit_states
    ]
    if not combinations:
        return 1
    nonlinear = settings.second_order or any(
        element.tension_only or element.comp_only for element in request.elements
    )
    exact_member_deflection = (
        any(
            element.deflection_limit is not None
            or element.deflection_ratio_limit is not None
            for element in request.elements
        )
        and bool(
            request.include_self_weight
            or request.member_point_loads
            or request.member_distributed_loads
            or request.load_panels
        )
    )
    distributed_member_loading = bool(
        request.include_self_weight
        or request.member_distributed_loads
        or request.load_panels
    )
    individual = settings.strategy == "individual" or (
        settings.strategy == "auto"
        and (nonlinear or exact_member_deflection or distributed_member_loading)
    )
    if individual:
        return len(combinations) * (2 if settings.second_order else 1)
    used_cases = {
        load_case_id
        for combination in combinations
        for load_case_id, factor in combination.factors.items()
        if abs(float(factor)) > 1.0e-15
    }
    basis_passes = max(1, len(used_cases))
    post_processing_passes = max(
        1,
        (len(combinations) + 3) // 4,
    )
    if settings.verify_profiles:
        uls_count = sum(
            combination.limit_state.startswith("uls_") for combination in combinations
        )
        post_processing_passes = max(
            post_processing_passes,
            (uls_count + 1) // 2,
        )
    return basis_passes + post_processing_passes


def estimate_calculation_requirements(request: SolveRequest) -> CalculationRequirements:
    node_count = len(request.nodes)
    element_count = len(request.elements)
    estimated_dof = node_count * 6
    load_item_count = estimate_load_item_count(request)
    analysis_pass_count = estimate_analysis_pass_count(request)
    effective_element_work = (
        element_count * max(ANALYSIS_PASS_BATCH_SIZE, analysis_pass_count)
        + ANALYSIS_PASS_BATCH_SIZE
        - 1
    ) // ANALYSIS_PASS_BATCH_SIZE
    required_class = highest_class(
        (
            classify_model_scale(node_count),
            classify_model_scale(element_count),
            classify_model_scale(load_item_count),
            classify_model_scale(effective_element_work),
        )
    )
    return CalculationRequirements(
        required_class=required_class,
        node_count=node_count,
        element_count=element_count,
        estimated_dof=estimated_dof,
        load_item_count=load_item_count,
        estimated_memory_mb=CLASS_MEMORY_MB[required_class],
    )
