from __future__ import annotations

import math
from dataclasses import dataclass

from ..domain import CalculationStep, CalculationValue, DesignStatus


GAMMA_A1 = 1.10
GAMMA_A2 = 1.35
DEMAND_EPSILON = 1.0e-6


@dataclass(frozen=True)
class CapacityResult:
    status: DesignStatus
    resistance: float | None
    steps: tuple[CalculationStep, ...]
    summary: str
    warnings: tuple[str, ...] = ()


def is_positive_finite(value: float | None) -> bool:
    return value is not None and math.isfinite(value) and value > 0.0


def utilization_status(demand: float, resistance: float) -> tuple[float, DesignStatus]:
    utilization = demand / resistance
    status = DesignStatus.PASSED if utilization <= 1.0 + 1.0e-12 else DesignStatus.FAILED
    return utilization, status


def value(symbol: str, label: str, raw: float | str | bool | None, unit: str = "") -> CalculationValue:
    return CalculationValue(symbol=symbol, label=label, value=raw, unit=unit)


def step(
    *,
    id: str,
    title: str,
    clause: str,
    explanation: str,
    formula: str,
    substitution: str,
    result_symbol: str,
    result_label: str,
    result_value: float | str | bool | None,
    result_unit: str = "",
    inputs: tuple[CalculationValue, ...] = (),
) -> CalculationStep:
    return CalculationStep(
        id=id,
        title=title,
        clause=clause,
        explanation=explanation,
        formula=formula,
        substitution=substitution,
        result=value(result_symbol, result_label, result_value, result_unit),
        inputs=inputs,
    )


def fmt(value_to_format: float, unit: str = "") -> str:
    scale = 1.0
    suffix = unit
    if unit == "Pa":
        scale, suffix = 1.0e-6, "MPa"
    elif unit == "N":
        scale, suffix = 1.0e-3, "kN"
    elif unit == "N.m":
        scale, suffix = 1.0e-3, "kN.m"
    elif unit == "m":
        scale, suffix = 1.0e3, "mm"
    elif unit == "m2":
        scale, suffix = 1.0e4, "cm2"
    elif unit == "m3":
        scale, suffix = 1.0e6, "cm3"
    elif unit == "m4":
        scale, suffix = 1.0e8, "cm4"
    elif unit == "m6":
        scale, suffix = 1.0e12, "cm6"
    rendered = f"{value_to_format * scale:.6g}"
    return f"{rendered} {suffix}".strip()
