from datetime import date
ALLOWED={'ADMIT','CONDITIONAL','REJECT','HOLD'}

def evaluate(c):
    missing=[k for k in ['admission_id','service_tier','sli_set','slo_target','sla_commitment','forecast_ref','p95_demand','tested_capacity','failover_reserve','cost_to_serve','price_or_value_basis','margin_floor','serviceability_state','evidence_freshness','evidence_ref'] if c.get(k) in (None,'',[])]
    tested=c.get('tested_capacity'); reserve=c.get('failover_reserve'); p95=c.get('p95_demand')
    eff=None if tested is None or reserve is None else round(tested-reserve,4)
    cap_margin=None if eff is None or p95 is None else round(eff-p95,4)
    cap_ratio=None if cap_margin is None or not p95 else cap_margin/p95
    qh=None
    if c.get('quota_limit') is not None and c.get('quota_current_usage') is not None: qh=round(c['quota_limit']-c['quota_current_usage'],4)
    commercial=None
    if c.get('price_or_value_basis') is not None and c.get('cost_to_serve') is not None: commercial=round(c['price_or_value_basis']-c['cost_to_serve'],4)
    fresh=bool(c.get('evidence_freshness_days') is not None and c['evidence_freshness_days']<=c.get('max_freshness_days',30))
    exception_valid=bool(c.get('exception_owner') and c.get('exception_days_remaining',-1)>=0)
    failover_quota_known=bool(c.get('failover_quota_known',False))
    reason='PASS'; state='ADMIT'
    if missing or c.get('serviceability_state') in ('UNKNOWN','DISPUTED',None) or not failover_quota_known:
        state='HOLD'; reason='DECISIVE_EVIDENCE_MISSING'
    elif not fresh:
        state='HOLD'; reason='EVIDENCE_STALE'
    elif eff is not None and p95 is not None and p95>eff:
        state='REJECT'; reason='TESTED_CAPACITY_SHORTFALL'
    elif qh is not None and p95 is not None and qh < p95 + reserve:
        state='REJECT'; reason='QUOTA_HEADROOM_SHORTFALL'
    elif commercial is not None and commercial < c.get('margin_floor',0):
        state='REJECT'; reason='MARGIN_FLOOR_BREACH'
    elif cap_ratio is not None and cap_ratio < 0.10:
        if exception_valid:
            state='CONDITIONAL'; reason='CAPACITY_BUFFER_EXCEPTION'
        else:
            state='REJECT'; reason='CAPACITY_BUFFER_BELOW_POLICY'
    trigger={
      'ADMIT':'review on material SLA, forecast, capacity, quota or cost change',
      'CONDITIONAL':'stop admission when exception expires or any hard constraint changes',
      'REJECT':'do not admit; repair named hard constraint and rerun the gate',
      'HOLD':'obtain/refresh decisive evidence and rerun before admission'
    }[state]
    return {'decision_state':state,'reason_code':reason,'effective_capacity':eff,'capacity_margin':cap_margin,'capacity_margin_ratio':None if cap_ratio is None else round(cap_ratio,6),'quota_headroom':qh,'commercial_margin':commercial,'evidence_fresh':fresh,'exception_valid':exception_valid,'missing_fields':missing,'stop_or_pivot_trigger':trigger,'evidence_ref':c.get('evidence_ref')}
