"""
Inscoper NBO Example Script: Import NBO-XML
===========================================
This script demonstrates how to populate an NBO object tree from an XML string or
from an XML file, and how imported documents are validated.

Prerequisites:
-------------
1. Installation: The `inscoper_nbo` wheel must be installed in the active Python
   environment.
2. Sample Data: This script reads `instrument_sample.xml`. Change SAMPLE_PATH
   below to the location where you saved it.
"""

# --8<-- [start:main_logic]
import inscoper_nbo

SAMPLE_PATH = "instrument_sample.xml"

# Step 1: Import from a string
# Importing replaces the whole content of the target object.
image = inscoper_nbo.Image()

image.fromXmlString(
    """<?xml version="1.0"?>
<Image ID="Image:1" Name="Field 1">
  <StageLabel Name="Position 0" X="0" Y="0" />
  <StageLabel Name="Position 1" X="120.5" Y="0" />
</Image>"""
)

print(image.getID().get(), image.getName().get())
print(len(image.getStageLabel_List()))

# Step 2: Import from a file
instrument = inscoper_nbo.Instrument()
instrument.fromXmlFile(SAMPLE_PATH)

print(instrument.getID().get())
for objective in instrument.getObjective_List():
    print(objective.getModel(), objective.getMagnification())

# Step 3: Imported documents are validated
# Values that violate a schema restriction raise InscoperNBOValidationException,
# which keeps invalid metadata out of the model.
non_compliant = """<?xml version="1.0"?>
<Image ID="NotAnImageIdentifier" />"""

try:
    image.fromXmlString(non_compliant)
except inscoper_nbo.InscoperNBOValidationException as error:
    print(f"Rejected document: {error}")

# Pass False to import a non-compliant document as it is
image.fromXmlString(non_compliant, False)
print(image.getID().get())
# --8<-- [end:main_logic]
