import math

def read_top_alternative(result):
    alternatives=result.get("alternatives",[])
    if not alternatives:
        return {"state":"no_alternative"}
    top=alternatives[0]  # Provider ordering, not max(confidence).
    if not isinstance(top.get("transcript"),str):
        raise ValueError("Bad transcript")
    if "confidence" not in top:
        return {"state":"score_missing","text":top["transcript"],"confidence":None}
    value=top["confidence"]
    if type(value) not in (int,float) or not math.isfinite(value) or not 0<=value<=1:
        raise ValueError("Bad confidence")
    return {"state":"score_present","text":top["transcript"],"confidence":value}

if __name__ == "__main__":
    samples=[
      {"alternatives":[{"transcript":"الف"}]},
      {"alternatives":[{"transcript":"ب","confidence":0.0}]},
      {"alternatives":[{"transcript":"گزینه نخست","confidence":0.4},{"transcript":"گزینه دوم","confidence":0.9}]},
      {"alternatives":[]},
    ]
    result=[read_top_alternative(x) for x in samples]
    assert result[0]["state"]=="score_missing"
    assert result[1]["confidence"]==0.0 and result[1]["state"]=="score_present"
    assert result[2]["text"]=="گزینه نخست"
    assert result[3]["state"]=="no_alternative"
    print(result)
    for bad in (None, True, -0.1, 1.1, float("nan")):
        try:read_top_alternative({"alternatives":[{"transcript":"x","confidence":bad}]})
        except ValueError:pass
        else:raise AssertionError("Invalid confidence accepted")
