"""Explain a synthetic ranking policy. Python 3.10+, standard library only."""
from decimal import Decimal, ROUND_HALF_UP
import json
from math import isfinite


def score_role(fit, attainability, weight=0.6, hard_cap=None):
    """Keep unknown attainability explicit; apply the hard cap after blending."""
    values = {'fit': (fit, 100), 'weight': (weight, 1)}
    if attainability is not None:
        values['attainability'] = (attainability, 100)
    if hard_cap is not None:
        values['hard_cap'] = (hard_cap, 100)
    for name, (value, maximum) in values.items():
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= maximum:
            raise ValueError(f'{name} must be a finite number between 0 and {maximum}')
    fit = Decimal(str(fit))
    weight = Decimal(str(weight))
    blended = fit if attainability is None else (1 - weight) * fit + weight * Decimal(str(attainability))
    final = min(blended, Decimal(str(hard_cap))) if hard_cap is not None else blended
    return {
        'blended': float(blended),
        'score': int(final.quantize(Decimal('1'), rounding=ROUND_HALF_UP)),
        'attainability_known': attainability is not None,
        'cap_applied': hard_cap is not None and final < blended,
    }


FIXTURE = [
    {'id': 'support', 'fit': 70, 'attainability': 90},
    {'id': 'data', 'fit': 75, 'attainability': 80},
    {'id': 'automation', 'fit': 88, 'attainability': 28},
    {'id': 'security', 'fit': 95, 'attainability': 88, 'hard_cap': 35},
    {'id': 'unknown', 'fit': 75, 'attainability': None},
]


def rank_roles(rows, weight=0.6):
    scored = [dict(id=row['id'], **score_role(row['fit'], row['attainability'], weight, row.get('hard_cap'))) for row in rows]
    return sorted(scored, key=lambda row: (-row['score'], row['id']))


if __name__ == '__main__':
    print(json.dumps({'default_weight': rank_roles(FIXTURE), 'fit_only': rank_roles(FIXTURE, 0)}, indent=2))
