from __future__ import annotations

import math

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


def shear_capacity(member: MemberDesignInput, *, direction: str) -> CapacityResult:
    section = member.section
    material = member.material
    if direction == "strong":
        required = {
            "d": section.depth_m,
            "d'": section.fillet_clear_web_height_m,
            "tw": section.web_thickness_m,
            "E": material.elastic_modulus_pa,
            "fy": material.yield_strength_pa,
        }
        kv = 5.34
        clear_dimension = section.fillet_clear_web_height_m
        thickness = section.web_thickness_m
        shear_area = (
            float(section.depth_m) * float(section.web_thickness_m)
            if is_positive_finite(section.depth_m) and is_positive_finite(section.web_thickness_m)
            else None
        )
        label = "paralela a alma (Vz local)"
        area_formula = "Aw = d tw"
        clause = "ABNT NBR 8800:2024, 5.4.3.1"
    elif direction == "weak":
        required = {
            "bf": section.flange_width_m,
            "tf": section.flange_thickness_m,
            "E": material.elastic_modulus_pa,
            "fy": material.yield_strength_pa,
        }
        kv = 1.20
        clear_dimension = (
            float(section.flange_width_m) / 2.0 if is_positive_finite(section.flange_width_m) else None
        )
        thickness = section.flange_thickness_m
        shear_area = (
            2.0 * float(section.flange_width_m) * float(section.flange_thickness_m)
            if is_positive_finite(section.flange_width_m) and is_positive_finite(section.flange_thickness_m)
            else None
        )
        label = "paralela as mesas (Vy local)"
        area_formula = "Aw = 2 bf tf"
        clause = "ABNT NBR 8800:2024, 5.4.3.5"
    else:
        raise ValueError(f"Direcao de cisalhamento invalida: {direction}")

    missing = [symbol for symbol, item in required.items() if not is_positive_finite(item)]
    if missing or not is_positive_finite(clear_dimension) or not is_positive_finite(thickness) or not is_positive_finite(shear_area):
        return CapacityResult(
            status=DesignStatus.INCOMPLETE,
            resistance=None,
            steps=(),
            summary=f"Dados ausentes para cisalhamento {label}: {', '.join(missing)}.",
        )

    elastic_modulus = float(material.elastic_modulus_pa)
    yield_strength = float(material.yield_strength_pa)
    clear_dimension = float(clear_dimension)
    thickness = float(thickness)
    shear_area = float(shear_area)
    slenderness = clear_dimension / thickness
    compact_limit = 1.10 * math.sqrt(kv * elastic_modulus / yield_strength)
    noncompact_limit = 1.37 * math.sqrt(kv * elastic_modulus / yield_strength)
    plastic_shear = 0.60 * shear_area * yield_strength
    if slenderness <= compact_limit:
        reduction = 1.0
        classification = "sem reducao por instabilidade"
        branch_formula = "Cv = 1.0"
    elif slenderness <= noncompact_limit:
        reduction = compact_limit / slenderness
        classification = "faixa intermediaria"
        branch_formula = "Cv = lambda_p/lambda"
    else:
        reduction = 1.24 * (compact_limit / slenderness) ** 2
        classification = "alma/mesa esbelta ao cisalhamento"
        branch_formula = "Cv = 1.24(lambda_p/lambda)^2"
    resistance = reduction * plastic_shear / GAMMA_A1
    steps = (
        step(
            id=f"shear-{direction}-slenderness",
            title=f"Esbeltez ao cisalhamento {label}",
            clause=clause,
            explanation=f"Para este caso, kv={kv:.2f}.",
            formula="lambda=h/t; lambda_p=1.10 sqrt(kv E/fy); lambda_r=1.37 sqrt(kv E/fy)",
            substitution=f"lambda={slenderness:.6g}; lambda_p={compact_limit:.6g}; lambda_r={noncompact_limit:.6g}",
            result_symbol="classe",
            result_label="Faixa de esbeltez ao cisalhamento",
            result_value=classification,
            inputs=(value("h", "Dimensao livre resistente", clear_dimension, "m"), value("t", "Espessura resistente", thickness, "m"), value("kv", "Coeficiente de flambagem", kv)),
        ),
        step(
            id=f"shear-{direction}-plastic",
            title=f"Forca cortante de plastificacao {label}",
            clause=clause,
            explanation="A area de cisalhamento segue a definicao especifica da direcao analisada.",
            formula=f"{area_formula}; Vpl = 0.60 Aw fy",
            substitution=f"Aw={fmt(shear_area, 'm2')}; Vpl=0.60 x {fmt(shear_area, 'm2')} x {fmt(yield_strength, 'Pa')}",
            result_symbol="Vpl",
            result_label="Forca cortante de plastificacao",
            result_value=plastic_shear,
            result_unit="N",
        ),
        step(
            id=f"shear-{direction}-resistance",
            title=f"Forca cortante resistente {label}",
            clause=clause,
            explanation="A plastificacao e reduzida quando a esbeltez ultrapassa lambda_p.",
            formula=f"{branch_formula}; VRd = Cv Vpl/gamma_a1",
            substitution=f"Cv={reduction:.8g}; Vpl={fmt(plastic_shear, 'N')}; gamma_a1={GAMMA_A1:.2f}",
            result_symbol="VRd",
            result_label="Forca cortante resistente de calculo",
            result_value=resistance,
            result_unit="N",
        ),
    )
    return CapacityResult(
        status=DesignStatus.PASSED,
        resistance=resistance,
        steps=steps,
        summary=f"Cisalhamento {label}: {classification}.",
    )
