from __future__ import annotations

from typing import Any, Literal

from pydantic import Field, model_validator

from .schemas import MAX_MEMBER_DESIGN_POINTS_PER_CASE, StrictModel


MAX_DESIGN_FORCE_CASES = 100
MAX_DESIGN_SEGMENTS = 500
MAX_DESIGN_BATCH_MEMBERS = 10_000
MAX_DESIGN_BATCH_FORCE_POINTS = 500_000
MAX_DESIGN_FORCE_N = 1.0e12
MAX_DESIGN_MOMENT_NM = 1.0e13
MAX_DESIGN_LENGTH_M = 1.0e6
MAX_DESIGN_MODULUS_PA = 1.0e13
MAX_DESIGN_AREA_M2 = 1.0e4
MAX_DESIGN_INERTIA_M4 = 1.0e8
MAX_DESIGN_WARPING_M6 = 1.0e12


class MemberDesignMaterialPayload(StrictModel):
    name: str = Field(..., min_length=1, max_length=120)
    grade: str | None = Field(default=None, max_length=120)
    elastic_modulus_pa: float | None = Field(default=None, gt=0, le=MAX_DESIGN_MODULUS_PA)
    shear_modulus_pa: float | None = Field(default=None, gt=0, le=MAX_DESIGN_MODULUS_PA)
    yield_strength_pa: float | None = Field(default=None, gt=0, le=MAX_DESIGN_MODULUS_PA)
    ultimate_strength_pa: float | None = Field(default=None, gt=0, le=MAX_DESIGN_MODULUS_PA)


class HotRolledISectionPayload(StrictModel):
    name: str = Field(..., min_length=1, max_length=160)
    profile_key: str | None = Field(default=None, max_length=120)
    source: str | None = Field(default=None, max_length=255)
    source_revision: str | None = Field(default=None, max_length=80)
    manufacturing_process: Literal["hot_rolled"] = "hot_rolled"
    shape: Literal["doubly_symmetric_i"] = "doubly_symmetric_i"
    area_m2: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2)
    inertia_strong_m4: float | None = Field(default=None, gt=0, le=MAX_DESIGN_INERTIA_M4)
    inertia_weak_m4: float | None = Field(default=None, gt=0, le=MAX_DESIGN_INERTIA_M4)
    torsional_constant_m4: float | None = Field(default=None, gt=0, le=MAX_DESIGN_INERTIA_M4)
    depth_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    flange_width_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    web_thickness_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    flange_thickness_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    clear_web_height_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    fillet_clear_web_height_m: float | None = Field(default=None, gt=0, le=MAX_DESIGN_LENGTH_M)
    elastic_modulus_strong_m3: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2 * MAX_DESIGN_LENGTH_M)
    elastic_modulus_weak_m3: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2 * MAX_DESIGN_LENGTH_M)
    plastic_modulus_strong_m3: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2 * MAX_DESIGN_LENGTH_M)
    plastic_modulus_weak_m3: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2 * MAX_DESIGN_LENGTH_M)
    warping_constant_m6: float | None = Field(default=None, gt=0, le=MAX_DESIGN_WARPING_M6)


class MemberDesignForcePointPayload(StrictModel):
    position_m: float = Field(..., ge=0, le=MAX_DESIGN_LENGTH_M)
    axial_n: float = Field(..., ge=-MAX_DESIGN_FORCE_N, le=MAX_DESIGN_FORCE_N)
    shear_local_y_n: float = Field(..., ge=-MAX_DESIGN_FORCE_N, le=MAX_DESIGN_FORCE_N)
    shear_local_z_n: float = Field(..., ge=-MAX_DESIGN_FORCE_N, le=MAX_DESIGN_FORCE_N)
    torsion_nm: float = Field(..., ge=-MAX_DESIGN_MOMENT_NM, le=MAX_DESIGN_MOMENT_NM)
    moment_local_y_nm: float = Field(..., ge=-MAX_DESIGN_MOMENT_NM, le=MAX_DESIGN_MOMENT_NM)
    moment_local_z_nm: float = Field(..., ge=-MAX_DESIGN_MOMENT_NM, le=MAX_DESIGN_MOMENT_NM)


class MemberDesignForceCasePayload(StrictModel):
    id: str = Field(..., min_length=1, max_length=80, pattern=r"^[A-Za-z0-9._:-]+$")
    name: str = Field(..., min_length=1, max_length=160)
    limit_state: Literal[
        "characteristic",
        "uls_normal",
        "uls_construction",
        "uls_exceptional",
        "uls_seismic",
        "sls_rare",
        "sls_frequent",
        "sls_quasi_permanent",
    ]
    points: list[MemberDesignForcePointPayload] = Field(
        ...,
        min_length=1,
        max_length=MAX_MEMBER_DESIGN_POINTS_PER_CASE,
    )
    factors: dict[str, float] = Field(default_factory=dict, max_length=200)


class MemberDesignUnbracedSegmentPayload(StrictModel):
    start_m: float = Field(..., ge=0, le=MAX_DESIGN_LENGTH_M)
    end_m: float = Field(..., gt=0, le=MAX_DESIGN_LENGTH_M)
    moment_gradient_factor: float | None = Field(default=None, gt=0, le=20.0)

    @model_validator(mode="after")
    def validate_range(self) -> "MemberDesignUnbracedSegmentPayload":
        if self.end_m <= self.start_m:
            raise ValueError("O fim do trecho destravado deve ser posterior ao inicio.")
        return self


class HotRolledIMemberDesignRequest(StrictModel):
    member_id: int = Field(..., ge=1, le=2_000_000_000)
    member_name: str = Field(..., min_length=1, max_length=160)
    length_m: float = Field(..., gt=0, le=MAX_DESIGN_LENGTH_M)
    material: MemberDesignMaterialPayload
    section: HotRolledISectionPayload
    force_cases: list[MemberDesignForceCasePayload] = Field(
        ...,
        min_length=1,
        max_length=MAX_DESIGN_FORCE_CASES,
    )
    buckling_factor_strong: float | None = Field(default=None, gt=0, le=100.0)
    buckling_factor_weak: float | None = Field(default=None, gt=0, le=100.0)
    buckling_factor_torsional: float | None = Field(default=None, gt=0, le=100.0)
    unbraced_segments: list[MemberDesignUnbracedSegmentPayload] = Field(
        default_factory=list,
        max_length=MAX_DESIGN_SEGMENTS,
    )
    continuous_lateral_restraint: bool = False
    connection_mode: Literal["unknown", "full_section", "custom"] = "unknown"
    net_area_m2: float | None = Field(default=None, gt=0, le=MAX_DESIGN_AREA_M2)
    shear_lag_factor: float | None = Field(default=None, gt=0, le=1.0)
    analysis_method: Literal[
        "unknown",
        "first_order",
        "second_order",
        "provided_design_forces",
    ] = "unknown"
    transverse_load_position: Literal["centroid", "unknown", "stabilizing", "destabilizing"] = "unknown"
    has_localized_transverse_forces: bool | None = None
    notes: list[str] = Field(default_factory=list, max_length=20)

    @model_validator(mode="after")
    def validate_member_design_input(self) -> "HotRolledIMemberDesignRequest":
        if self.connection_mode == "custom":
            if self.net_area_m2 is None or self.shear_lag_factor is None:
                raise ValueError("Ligacao personalizada exige area liquida e coeficiente Ct.")
            if self.section.area_m2 is not None and self.net_area_m2 > self.section.area_m2:
                raise ValueError("A area liquida nao pode superar a area bruta.")
        elif self.net_area_m2 is not None or self.shear_lag_factor is not None:
            raise ValueError("An e Ct so podem ser informados em ligacao personalizada.")
        for force_case in self.force_cases:
            if any(point.position_m > self.length_m + 1.0e-9 for point in force_case.points):
                raise ValueError(f"O caso {force_case.name} contem ponto fora do comprimento da barra.")
        ordered_segments = sorted(self.unbraced_segments, key=lambda item: (item.start_m, item.end_m))
        for index, segment in enumerate(ordered_segments):
            if segment.end_m > self.length_m + 1.0e-9:
                raise ValueError("Trecho destravado fora do comprimento da barra.")
            if index and segment.start_m < ordered_segments[index - 1].end_m - 1.0e-9:
                raise ValueError("Trechos destravados nao podem se sobrepor.")
        if self.continuous_lateral_restraint and self.unbraced_segments:
            raise ValueError("Contencao lateral continua nao admite trechos destravados simultaneamente.")
        if any(not note.strip() or len(note) > 255 for note in self.notes):
            raise ValueError("Cada nota deve ter entre 1 e 255 caracteres.")
        return self


class CalculationValueResponse(StrictModel):
    symbol: str
    label: str
    value: float | str | bool | None
    unit: str = ""


class CalculationStepResponse(StrictModel):
    id: str
    title: str
    clause: str
    explanation: str
    formula: str
    substitution: str
    result: CalculationValueResponse
    inputs: tuple[CalculationValueResponse, ...] = ()


class MemberDesignCheckResponse(StrictModel):
    id: str
    title: str
    clause: str
    status: Literal["passed", "failed", "incomplete", "not_applicable"]
    summary: str
    demand: float | None = None
    resistance: float | None = None
    utilization: float | None = None
    unit: str = ""
    governing_case_id: str | None = None
    governing_case_name: str | None = None
    governing_position_m: float | None = None
    steps: tuple[CalculationStepResponse, ...] = ()
    warnings: tuple[str, ...] = ()


class HotRolledIMemberDesignResponse(StrictModel):
    member_id: int | str
    member_name: str
    standard: str
    module: str
    module_version: str
    status: Literal["passed", "failed", "incomplete", "not_applicable"]
    summary: str
    governing_check_id: str | None = None
    governing_utilization: float | None = None
    checks: tuple[MemberDesignCheckResponse, ...]
    assumptions: tuple[str, ...]
    limitations: tuple[str, ...]
    input_snapshot: dict[str, Any]


class HotRolledIMemberDesignBatchRequest(StrictModel):
    members: list[HotRolledIMemberDesignRequest] = Field(
        ...,
        min_length=1,
        max_length=MAX_DESIGN_BATCH_MEMBERS,
    )
    detail_member_id: int | None = Field(default=None, ge=1, le=2_000_000_000)

    @model_validator(mode="after")
    def validate_batch(self) -> "HotRolledIMemberDesignBatchRequest":
        member_ids: set[int | str] = set()
        for member in self.members:
            if member.member_id in member_ids:
                raise ValueError("Cada barra pode aparecer apenas uma vez no lote de dimensionamento.")
            member_ids.add(member.member_id)
        if self.detail_member_id is not None and self.detail_member_id not in member_ids:
            raise ValueError("A barra solicitada para detalhamento nao pertence ao lote.")
        point_count = sum(
            len(force_case.points)
            for member in self.members
            for force_case in member.force_cases
        )
        if point_count > MAX_DESIGN_BATCH_FORCE_POINTS:
            raise ValueError(
                "O lote excede o limite de pontos de esforcos; divida a verificacao em selecoes menores."
            )
        return self


class CompactHotRolledIMemberDesignBatchRequest(StrictModel):
    format: Literal["fse3d.member-design.columnar.v1"]
    members: dict[str, Any]
    detail_member_id: int | None = Field(default=None, ge=1, le=2_000_000_000)


class HotRolledIMemberDesignSummaryResponse(StrictModel):
    member_id: int | str
    member_name: str
    status: Literal["passed", "failed", "incomplete", "not_applicable"]
    summary: str
    governing_check_id: str | None = None
    governing_check_title: str | None = None
    governing_utilization: float | None = None
    failed_check_ids: tuple[str, ...] = ()
    incomplete_check_ids: tuple[str, ...] = ()


class HotRolledIMemberDesignBatchResponse(StrictModel):
    standard: str
    module: str
    module_version: str
    total: int
    passed: int
    failed: int
    incomplete: int
    not_applicable: int
    results: tuple[HotRolledIMemberDesignSummaryResponse, ...]
    detail: HotRolledIMemberDesignResponse | None = None


class CompactHotRolledIMemberDesignBatchResponse(StrictModel):
    format: Literal["fse3d.member-design-result.columnar.v1"]
    standard: str
    module: str
    module_version: str
    total: int
    passed: int
    failed: int
    incomplete: int
    not_applicable: int
    results: dict[str, Any]
    detail: HotRolledIMemberDesignResponse | None = None
