import xml.etree.ElementTree as ET
from typing import Sequence

from .types import CompletedPart


def generate_complete_multipart_xml(parts: Sequence[CompletedPart]) -> str:
    if not parts:
        raise ValueError("parts 不能为空")

    root = ET.Element("CompleteMultipartUpload")
    for part in sorted(parts, key=lambda p: p["PartNumber"]):
        part_number = part["PartNumber"]
        etag = part["ETag"]
        part_el = ET.SubElement(root, "Part")
        ET.SubElement(part_el, "PartNumber").text = str(part_number)
        ET.SubElement(part_el, "ETag").text = etag
    return ET.tostring(root, encoding="utf-8", method="xml").decode("utf-8")
