from __future__ import annotations

import math

from ..domain import DesignStatus, MemberDesignInput
from .common import GAMMA_A1, CapacityResult, fmt, is_positive_finite, step, value


def compression_slenderness_ratios(member: MemberDesignInput) -> tuple[float, float, float] | None:
    section = member.section
    area = section.area_m2
    iy = section.inertia_strong_m4
    iz = section.inertia_weak_m4
    if not all(
        is_positive_finite(item)
        for item in (
            area,
            iy,
            iz,
            member.length_m,
            member.buckling_factor_strong,
            member.buckling_factor_weak,
            member.buckling_factor_torsional,
        )
    ):
        return None
    radius_strong = math.sqrt(float(iy) / float(area))
    radius_weak = math.sqrt(float(iz) / float(area))
    return (
        float(member.buckling_factor_strong) * member.length_m / radius_strong,
        float(member.buckling_factor_weak) * member.length_m / radius_weak,
        float(member.buckling_factor_torsional) * member.length_m / math.sqrt(radius_strong**2 + radius_weak**2),
    )


def compression_capacity(member: MemberDesignInput) -> CapacityResult:
    section = member.section
    material = member.material
    required = {
        "A": section.area_m2,
        "Iy": section.inertia_strong_m4,
        "Iz": section.inertia_weak_m4,
        "J": section.torsional_constant_m4,
        "d": section.depth_m,
        "bf": section.flange_width_m,
        "tw": section.web_thickness_m,
        "tf": section.flange_thickness_m,
        "h": section.fillet_clear_web_height_m,
        "E": material.elastic_modulus_pa,
        "G": material.shear_modulus_pa,
        "fy": material.yield_strength_pa,
        "Ky": member.buckling_factor_strong,
        "Kz": member.buckling_factor_weak,
        "Kt": member.buckling_factor_torsional,
    }
    missing = [symbol for symbol, item in required.items() if not is_positive_finite(item)]
    if missing:
        return CapacityResult(
            status=DesignStatus.INCOMPLETE,
            resistance=None,
            steps=(),
            summary=f"Dados ausentes ou invalidos para compressao: {', '.join(missing)}.",
        )

    area = float(section.area_m2)
    iy = float(section.inertia_strong_m4)
    iz = float(section.inertia_weak_m4)
    torsional_constant = float(section.torsional_constant_m4)
    depth = float(section.depth_m)
    flange_width = float(section.flange_width_m)
    web_thickness = float(section.web_thickness_m)
    flange_thickness = float(section.flange_thickness_m)
    # Para perfis laminados, h e a parte plana da alma entre os pes dos
    # filetes, e nao apenas a distancia entre as faces internas das mesas.
    clear_web_height = float(section.fillet_clear_web_height_m)
    elastic_modulus = float(material.elastic_modulus_pa)
    shear_modulus = float(material.shear_modulus_pa)
    yield_strength = float(material.yield_strength_pa)
    length = float(member.length_m)

    if length <= 0.0:
        return CapacityResult(
            status=DesignStatus.INCOMPLETE,
            resistance=None,
            steps=(),
            summary="O comprimento da barra deve ser positivo.",
        )

    radius_strong = math.sqrt(iy / area)
    radius_weak = math.sqrt(iz / area)
    polar_radius_squared = radius_strong**2 + radius_weak**2
    warping_constant = section.warping_constant_m6
    warping_source = "catalogo"
    if not is_positive_finite(warping_constant):
        warping_constant = iz * (depth - flange_thickness) ** 2 / 4.0
        warping_source = "D.2.8-a"
    warping_constant = float(warping_constant)

    effective_length_strong = float(member.buckling_factor_strong) * length
    effective_length_weak = float(member.buckling_factor_weak) * length
    effective_length_torsional = float(member.buckling_factor_torsional) * length
    if min(effective_length_strong, effective_length_weak, effective_length_torsional) <= 0.0:
        return CapacityResult(
            status=DesignStatus.INCOMPLETE,
            resistance=None,
            steps=(),
            summary="Os fatores de comprimento de flambagem devem ser positivos.",
        )

    ne_strong = math.pi**2 * elastic_modulus * iy / effective_length_strong**2
    ne_weak = math.pi**2 * elastic_modulus * iz / effective_length_weak**2
    ne_torsional = (
        math.pi**2 * elastic_modulus * warping_constant / effective_length_torsional**2
        + shear_modulus * torsional_constant
    ) / polar_radius_squared
    elastic_buckling = min(ne_strong, ne_weak, ne_torsional)
    governing_mode = min(
        (("flexao no eixo forte", ne_strong), ("flexao no eixo fraco", ne_weak), ("torcao", ne_torsional)),
        key=lambda item: item[1],
    )[0]
    reduced_slenderness = math.sqrt(area * yield_strength / elastic_buckling)
    if reduced_slenderness <= 1.5:
        reduction_factor = 0.658 ** (reduced_slenderness**2)
        chi_formula = "chi = 0.658^(lambda0^2)"
    else:
        reduction_factor = 0.877 / reduced_slenderness**2
        chi_formula = "chi = 0.877/lambda0^2"

    flange_half_width = flange_width / 2.0
    flange_lambda = flange_half_width / flange_thickness
    web_lambda = clear_web_height / web_thickness
    flange_limit = 0.56 * math.sqrt(elastic_modulus / yield_strength)
    web_limit = 1.49 * math.sqrt(elastic_modulus / yield_strength)
    flange_effective = _effective_plate_width(
        width=flange_half_width,
        slenderness=flange_lambda,
        limit=flange_limit,
        reduction_factor=reduction_factor,
        yield_strength=yield_strength,
        c1=0.22,
        c2=1.49,
    )
    web_effective = _effective_plate_width(
        width=clear_web_height,
        slenderness=web_lambda,
        limit=web_limit,
        reduction_factor=reduction_factor,
        yield_strength=yield_strength,
        c1=0.18,
        c2=1.31,
    )
    area_reduction = (
        4.0 * max(0.0, flange_half_width - flange_effective) * flange_thickness
        + max(0.0, clear_web_height - web_effective) * web_thickness
    )
    effective_area = min(area, max(1.0e-18, area - area_reduction))
    resistance = reduction_factor * effective_area * yield_strength / GAMMA_A1

    steps = (
        step(
            id="compression-radii",
            title="Raios de giracao",
            clause="ABNT NBR 8800:2024, 5.3.5.1 e Anexo B",
            explanation="Os raios sao obtidos das propriedades brutas nos eixos locais resistente forte e fraco.",
            formula="r = sqrt(I/A)",
            substitution=f"ry = sqrt({fmt(iy, 'm4')}/{fmt(area, 'm2')}); rz = sqrt({fmt(iz, 'm4')}/{fmt(area, 'm2')})",
            result_symbol="ry; rz",
            result_label="Raios de giracao forte e fraco",
            result_value=f"{fmt(radius_strong, 'm')}; {fmt(radius_weak, 'm')}",
            inputs=(value("A", "Area bruta", area, "m2"), value("Iy", "Inercia forte", iy, "m4"), value("Iz", "Inercia fraca", iz, "m4")),
        ),
        step(
            id="compression-warping",
            title="Constante de empenamento",
            clause="ABNT NBR 8800:2024, D.2.8-a",
            explanation=f"Constante de empenamento proveniente de {warping_source}.",
            formula="Cw = Iz (d - tf)^2 / 4, quando calculada",
            substitution=f"Cw = {fmt(warping_constant, 'm6')}",
            result_symbol="Cw",
            result_label="Constante de empenamento",
            result_value=warping_constant,
            result_unit="m6",
        ),
        step(
            id="compression-elastic-buckling",
            title="Forcas criticas elasticas",
            clause="ABNT NBR 8800:2024, 5.3.5.1 e Anexo B",
            explanation="Calculam-se os modos por flexao nos dois eixos e por torcao; governa o menor valor.",
            formula="Ne = min(pi^2 E Iy/(KyL)^2; pi^2 E Iz/(KzL)^2; [pi^2 E Cw/(KtL)^2 + GJ]/r0^2)",
            substitution=f"Ney={fmt(ne_strong, 'N')}; Nez={fmt(ne_weak, 'N')}; Net={fmt(ne_torsional, 'N')}",
            result_symbol="Ne",
            result_label=f"Forca critica elastica ({governing_mode})",
            result_value=elastic_buckling,
            result_unit="N",
        ),
        step(
            id="compression-reduced-slenderness",
            title="Indice de esbeltez reduzido",
            clause="ABNT NBR 8800:2024, 5.3.3",
            explanation="Relaciona a plastificacao da area bruta com a menor carga critica elastica.",
            formula="lambda0 = sqrt(A fy / Ne)",
            substitution=f"lambda0 = sqrt({fmt(area, 'm2')} x {fmt(yield_strength, 'Pa')} / {fmt(elastic_buckling, 'N')})",
            result_symbol="lambda0",
            result_label="Indice de esbeltez reduzido",
            result_value=reduced_slenderness,
        ),
        step(
            id="compression-reduction-factor",
            title="Fator de reducao global",
            clause="ABNT NBR 8800:2024, 5.3.3",
            explanation="O ramo da curva e escolhido pelo valor de lambda0.",
            formula=chi_formula,
            substitution=f"chi = {reduction_factor:.8g}",
            result_symbol="chi",
            result_label="Fator de reducao associado a compressao",
            result_value=reduction_factor,
        ),
        _effective_width_step(
            id="compression-effective-flange",
            title="Largura efetiva das mesas",
            element="AL",
            width=flange_half_width,
            thickness=flange_thickness,
            limit=flange_limit,
            reduction_factor=reduction_factor,
            effective_width=flange_effective,
            c1=0.22,
            c2=1.49,
            yield_strength=yield_strength,
        ),
        _effective_width_step(
            id="compression-effective-web",
            title="Largura efetiva da alma",
            element="AA",
            width=clear_web_height,
            thickness=web_thickness,
            limit=web_limit,
            reduction_factor=reduction_factor,
            effective_width=web_effective,
            c1=0.18,
            c2=1.31,
            yield_strength=yield_strength,
        ),
        step(
            id="compression-effective-area",
            title="Area efetiva",
            clause="ABNT NBR 8800:2024, 5.3.4.2",
            explanation="As parcelas inefetivas das quatro abas de mesa e da alma sao descontadas da area bruta.",
            formula="Aef = Ag - 4(bf/2 - bef,f)tf - (h - bef,w)tw",
            substitution=f"Aef = {fmt(area, 'm2')} - {fmt(area_reduction, 'm2')}",
            result_symbol="Aef",
            result_label="Area efetiva a compressao",
            result_value=effective_area,
            result_unit="m2",
        ),
        step(
            id="compression-resistance",
            title="Forca axial resistente a compressao",
            clause="ABNT NBR 8800:2024, 5.3.2",
            explanation="Resistencia de calculo considerando instabilidade global e local.",
            formula="Nc,Rd = chi Aef fy / gamma_a1",
            substitution=f"Nc,Rd = {reduction_factor:.6g} x {fmt(effective_area, 'm2')} x {fmt(yield_strength, 'Pa')} / {GAMMA_A1:.2f}",
            result_symbol="Nc,Rd",
            result_label="Forca resistente de calculo a compressao",
            result_value=resistance,
            result_unit="N",
        ),
    )
    return CapacityResult(
        status=DesignStatus.PASSED,
        resistance=resistance,
        steps=steps,
        summary=f"Resistencia a compressao calculada; modo elastico governante: {governing_mode}.",
    )


def _effective_plate_width(
    *,
    width: float,
    slenderness: float,
    limit: float,
    reduction_factor: float,
    yield_strength: float,
    c1: float,
    c2: float,
) -> float:
    if slenderness <= limit / math.sqrt(reduction_factor):
        return width
    elastic_stress = (c2 * limit / slenderness) ** 2 * yield_strength
    ratio = math.sqrt(elastic_stress / (reduction_factor * yield_strength))
    return min(width, max(0.0, width * (1.0 - c1 * ratio) * ratio))


def _effective_width_step(
    *,
    id: str,
    title: str,
    element: str,
    width: float,
    thickness: float,
    limit: float,
    reduction_factor: float,
    effective_width: float,
    c1: float,
    c2: float,
    yield_strength: float,
):
    slenderness = width / thickness
    threshold = limit / math.sqrt(reduction_factor)
    if slenderness <= threshold:
        formula = "bef = b, pois b/t <= (b/t)lim/sqrt(chi)"
        substitution = f"{slenderness:.6g} <= {threshold:.6g}"
    else:
        elastic_stress = (c2 * limit / slenderness) ** 2 * yield_strength
        ratio = math.sqrt(elastic_stress / (reduction_factor * yield_strength))
        formula = "sigma_el = [c2 (b/t)lim/(b/t)]^2 fy; bef = b[1-c1 sqrt(sigma_el/(chi fy))]sqrt(sigma_el/(chi fy))"
        substitution = f"sigma_el={fmt(elastic_stress, 'Pa')}; sqrt(sigma_el/(chi fy))={ratio:.6g}"
    return step(
        id=id,
        title=title,
        clause="ABNT NBR 8800:2024, 5.3.4.2 e Tabela 4",
        explanation=f"Elemento {element}; c1={c1:.2f} e c2={c2:.2f}.",
        formula=formula,
        substitution=substitution,
        result_symbol="bef",
        result_label="Largura efetiva",
        result_value=effective_width,
        result_unit="m",
        inputs=(
            value("b", "Largura do elemento", width, "m"),
            value("t", "Espessura do elemento", thickness, "m"),
            value("b/t", "Esbeltez local", slenderness),
            value("(b/t)lim", "Limite de plastificacao", limit),
        ),
    )
