defmodule TradeMachine.GMGradeV2.Pillars.ContractHealth do @moduledoc """ Aggregates AVC's four Contract Health metrics over the final roster. Contract Value, Long-Term Risk, Contract Mobility, and Contract Optionality retain full precision through the fixed 35/30/20/15 weighted sum. """ alias TradeMachine.GMGradeV2.Benchmark alias TradeMachine.GMGradeV2.ChallengeSnapshot alias TradeMachine.GMGradeV2.Pillars.ContractHealth.ContractMobility alias TradeMachine.GMGradeV2.Pillars.ContractHealth.ContractOptionality alias TradeMachine.GMGradeV2.Pillars.ContractHealth.ContractValue alias TradeMachine.GMGradeV2.Pillars.ContractHealth.LongTermRisk alias TradeMachine.GMGradeV2.Result.MetricResult alias TradeMachine.GMGradeV2.Result.PillarResult alias TradeMachine.GMGradeV2.Weighting @metric_weights %{ contract_value: 0.35, long_term_risk: 0.30, contract_mobility: 0.20, contract_optionality: 0.15 } @metric_modules [ ContractValue, LongTermRisk, ContractMobility, ContractOptionality ] if abs(Enum.sum(Map.values(@metric_weights)) - 1.0) > 1.0e-9 do raise "Contract Health metric weights must sum to 1.0" end @doc """ The published metric weights this pillar aggregates with. Public so the parameter registry and the model-document seed can read the authored weights instead of restating them (plan §5.1). """ @spec metric_weights() :: %{atom() => float()} def metric_weights, do: @metric_weights @doc """ Returns the full-precision Contract Health pillar result. `weights` defaults to the published `metric_weights/0`; a resolved grading model supplies its own set (plan §5.1). """ @spec score(map(), ChallengeSnapshot.t(), Weighting.weights()) :: PillarResult.t() def score( scenario_state, %ChallengeSnapshot{benchmark: %Benchmark{} = benchmark} = snapshot, weights \\ @metric_weights ) when is_map(scenario_state) do metric_results = Enum.map(@metric_modules, & &1.score(scenario_state, snapshot)) {strongest, weakest} = extrema(metric_results) %PillarResult{ key: :contract_health, version: benchmark.version, score: Weighting.combine(metric_results, weights), metric_results: metric_results, metric_weights: weights, explanation: explanation(strongest, weakest), strongest: strongest.key, weakest: weakest.key } end defp extrema(metric_results) do { Enum.max_by(metric_results, & &1.score), Enum.min_by(metric_results, & &1.score) } end defp explanation( %MetricResult{key: strongest_key, score: strongest_score}, %MetricResult{key: weakest_key, score: weakest_score} ) do "Contract Health combines four final-roster contract metrics; " <> "#{label(strongest_key)} is strongest at #{strongest_score}, while " <> "#{label(weakest_key)} is weakest at #{weakest_score}." end defp label(:contract_value), do: "Contract Value" defp label(:long_term_risk), do: "Long-Term Risk" defp label(:contract_mobility), do: "Contract Mobility" defp label(:contract_optionality), do: "Contract Optionality" end