import math

def map_segments(chunks):
    rows=[];seen=set()
    for chunk in chunks:
        offset=chunk["offset_seconds"]
        if type(offset) not in (int,float) or not math.isfinite(offset) or offset<0:
            raise ValueError("Bad chunk offset")
        for segment in chunk["segments"]:
            start,end=segment["start_seconds"],segment["end_seconds"]
            if not all(type(x) in (int,float) and math.isfinite(x) for x in (start,end)) or start<0 or end<=start:
                raise ValueError("Bad segment times")
            key=(chunk["chunk_id"],segment["segment_id"])
            if key in seen:raise ValueError("Duplicate segment identifier")
            seen.add(key)
            rows.append({"source_key":list(key),"start_seconds":offset+start,
              "end_seconds":offset+end,"text":segment["text"]})
    rows.sort(key=lambda r:(r["start_seconds"],r["end_seconds"],r["source_key"]))
    latest_end=-1
    for row in rows:
        row["overlap_requires_review"]=row["start_seconds"]<latest_end
        latest_end=max(latest_end,row["end_seconds"])
    return rows

if __name__=="__main__":
    chunks=[
      {"chunk_id":"a","offset_seconds":0,"segments":[{"segment_id":"1","start_seconds":8,"end_seconds":10,"text":"نه، ارسال نکنید"}]},
      {"chunk_id":"b","offset_seconds":9,"segments":[{"segment_id":"1","start_seconds":0,"end_seconds":1,"text":"ارسال نکنید"},{"segment_id":"2","start_seconds":2,"end_seconds":3,"text":"نه، ارسال نکنید"}]}
    ]
    result=map_segments(chunks)
    assert len(result)==3
    assert result[1]["start_seconds"]==9 and result[1]["overlap_requires_review"]
    assert result[2]["start_seconds"]==11 and not result[2]["overlap_requires_review"]
    assert result[0]["text"]==result[2]["text"] # genuine repetition is not deleted
    print(result)
