"""Atomic R2 Start projection, compatible with periodic old Web requests."""
import logging
import math
import re
from .config import R2ConfigError,score_floor,block
LOG=logging.getLogger(__name__)

def apply_parameters(spec,request):
    from app.fall_runtime import FallSettings
    raw=request.get('parameters');current=FallSettings.parse(spec.get('fall') or {})
    if current.engine!='r2':
        if type(raw) is dict and 'fall_r2' in raw:raise R2ConfigError('FALL_R2_NOT_ENABLED')
        return None
    if raw is None:raw={}
    if type(raw) is not dict:
        LOG.info('fall_r2_parameter_ignored parameter=parameters reason=INVALID_CONTAINER');raw={}
    explicit='fall_r2' in raw;cfg=current.settings_payload()
    cooldown=(spec.get('event_cooldowns') or {}).get('FALL',10.)
    reset=block(raw['fall_r2'],request=True) if explicit else False
    common={'person_confidence','pose_confidence','cooldown_seconds'}
    if reset:
        if common & set(raw):raise R2ConfigError('FALL_R2_RESET_INVALID')
        cfg.update(person_score=.25,joint_score=.10);cooldown=10.
    for key,private,minimum in (('person_confidence','person_score',.25),('pose_confidence','joint_score',.10)):
        if key not in raw:continue
        try:value=score_floor(raw[key],minimum)
        except R2ConfigError:
            if explicit:raise
            LOG.info('fall_r2_parameter_ignored parameter=%s reason=INVALID_VALUE',key);continue
        cfg[private]=value
        LOG.info('fall_r2_parameter parameter=%s requested=%s effective=%s corrected=%s',key,raw[key],value,value!=raw[key])
    if 'cooldown_seconds' in raw:
        v=raw['cooldown_seconds']
        try:valid=type(v) in (int,float) and math.isfinite(v) and 0<=v<=300
        except OverflowError:valid=False
        if not valid:
            if explicit:raise R2ConfigError('FALL_R2_COOLDOWN_INVALID')
            LOG.info('fall_r2_parameter_ignored parameter=cooldown_seconds reason=INVALID_VALUE')
        else:cooldown=float(v)
    for key in sorted(set(raw)-common-{'fall_r2'}):
        safe=key if isinstance(key,str) and re.fullmatch(r'[A-Za-z0-9_]{1,64}',key) else 'INVALID_KEY'
        reason='LEGACY_NOT_APPLIED' if key in ('down_angle_deg','recovery_hold_seconds') else 'UNKNOWN_PARAMETER'
        LOG.info('fall_r2_parameter_ignored parameter=%s reason=%s',safe,reason)
    cfg=FallSettings.parse(cfg).settings_payload()
    spec['fall']=cfg;spec.setdefault('event_cooldowns',{})['FALL']=cooldown
    LOG.info('fall_r2_effective version=1 person_score=%s joint_score=%s cooldown=%s',cfg['person_score'],cfg['joint_score'],cooldown)
    return True
