"""
Inscoper NBO Example Script: Export NBO-XML
===========================================
This script demonstrates how to serialize an NBO object tree to an XML string or
to an XML file, and how validation is applied on export.

Prerequisites:
-------------
1. Installation: The `inscoper_nbo` wheel must be installed in the active Python
   environment.
"""

# --8<-- [start:main_logic]
import os
import tempfile

import inscoper_nbo

# Build a small tree: an image carrying three stage positions
image = inscoper_nbo.Image()

image_id = inscoper_nbo.ImageID_Type()
image_id.set("Image:1")
image.setID(image_id)

name = inscoper_nbo.Denomination_Type()
name.set("Field 1")
image.setName(name)

for index, (x, y) in enumerate([(0.0, 0.0), (120.5, 0.0), (241.0, 0.0)]):
    stage_label = inscoper_nbo.StageLabel()
    stage_label.setName(f"Position {index}")
    stage_label.setX(x)
    stage_label.setY(y)
    image.addToStageLabel_List(stage_label)

# Step 1: Serialize to a string
print(image.toXmlString())

# Step 2: Serialize to a file
output_path = os.path.join(tempfile.gettempdir(), "image.xml")
image.toXmlFile(output_path)
print(f"Written to {output_path}")

# Step 3: Control validation on export
# Export validates the document by default: an element missing a required
# attribute raises InscoperNBOValidationException, and attributes that carry a
# schema default are written explicitly. Pass False to write exactly what was
# set, at the cost of producing a document that may not be schema-valid.
bin_data = inscoper_nbo.BinData()
bin_data.setBigEndian(True)
length = inscoper_nbo.NonNegativeLong_Type()
length.set(12)
bin_data.setLength(length)

print(bin_data.toXmlString())        # validated: Compression="none" is written
print(bin_data.toXmlString(False))   # as set: Compression is omitted
# --8<-- [end:main_logic]
