"""R5-CONFIG-01: old tuning is ignored, invalid explicit new tuning is atomic."""
import logging
import math
import re
from .config import R5ConfigError, LEGACY_PARAMETERS, score_floor

LOG=logging.getLogger(__name__)


def apply_parameters(spec, request):
    from app.fight_runtime import FightSettings
    from app.event_cooldown import default_seconds
    raw=request.get('parameters')
    current=FightSettings.parse(spec.get('fight') or {})
    if current.engine!='r5':
        if type(raw) is dict and 'fight_r5' in raw:raise R5ConfigError('FIGHT_R5_NOT_ENABLED')
        return None
    if raw is None:raw={}
    if type(raw) is not dict:
        LOG.info('fight_r5_parameter_ignored parameter=parameters reason=INVALID_CONTAINER')
        raw={}
    explicit='fight_r5' in raw
    cfg=current.settings_payload()
    if explicit:cfg['r5']=current.r5.patched(raw['fight_r5']).payload()
    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 R5ConfigError:
            if explicit:raise
            LOG.info('fight_r5_parameter_ignored parameter=%s reason=INVALID_VALUE',key)
            continue
        cfg[private]=value
        LOG.info('fight_r5_parameter parameter=%s requested=%s effective=%s corrected=%s',key,raw[key],value,value!=raw[key])
    cooldown=(spec.get('event_cooldowns') or {}).get('FIGHT',default_seconds())
    if 'cooldown_seconds' in raw:
        v=raw['cooldown_seconds']
        valid=type(v) in (int,float)
        try:valid=valid and math.isfinite(v) and 0<=v<=300
        except OverflowError:valid=False
        if not valid:
            if explicit:raise R5ConfigError('FIGHT_R5_COOLDOWN_INVALID')
            LOG.info('fight_r5_parameter_ignored parameter=cooldown_seconds reason=INVALID_VALUE')
        else:cooldown=float(v)
    common={'person_confidence','pose_confidence','cooldown_seconds','fight_r5'}
    for key in sorted(set(raw)-common):
        reason='LEGACY_NOT_APPLIED' if key in LEGACY_PARAMETERS else 'UNKNOWN_PARAMETER'
        safe=key if isinstance(key,str) and re.fullmatch(r'[A-Za-z0-9_]{1,64}',key) else 'INVALID_KEY'
        LOG.info('fight_r5_parameter_ignored parameter=%s reason=%s',safe,reason)
    # Diagnostic requested values never enter persisted config/no-op identity.
    cfg=FightSettings.parse(cfg).settings_payload()
    spec['fight']=cfg;spec.setdefault('event_cooldowns',{})['FIGHT']=cooldown
    LOG.info('fight_r5_effective version=1 person_score=%s joint_score=%s window=%s samples=%s contact_samples=%s cooldown=%s',
        cfg['person_score'],cfg['joint_score'],cfg['r5']['window_seconds'],cfg['r5']['min_samples'],cfg['r5']['contact_min_samples'],cooldown)
    return True
