"""Explicit structure-only recovery; malformed observations are never factual labels."""
import json

from .pallet_description_supervision import parse_prediction


def decode_output(raw):
    strict=parse_prediction(raw)
    if strict['valid']:
        return {**strict,'structure_recovered':False,'observation_withheld':False,'recovered_fields':None}
    try:
        prefix=raw.split(',"观察":',1)
        if len(prefix)!=2:raise ValueError('No structure/observation boundary')
        value=json.loads(prefix[0]+'}')
        if not isinstance(value,dict) or set(value)!={'支腿','横梁','材质','结构'}:raise ValueError('Unexpected structure keys')
        if type(value['支腿']) not in (int,type(None)) or value['支腿'] not in (None,2,3,4):raise ValueError('Invalid leg count')
        if type(value['横梁']) not in (int,type(None)) or value['横梁'] not in (None,1,2):raise ValueError('Invalid beam count')
        if value['材质'] not in ('塑料','木质','金属','无法判断') or not isinstance(value['结构'],str) or len(value['结构'])>2000:raise ValueError('Invalid structure')
    except (ValueError,TypeError,KeyError):
        return {**strict,'structure_recovered':False,'observation_withheld':True,'recovered_fields':None}
    return {**strict,'structure_recovered':True,'observation_withheld':True,'recovered_fields':{**value,'观察':None},
        'recovery_policy':'actual_generated_structure_only_malformed_observation_withheld_no_class_template_or_human_note_used'}
