"""
Inscoper NBO Example Script: Import a MicroMetaApp Configuration
===============================================================
This script demonstrates how to populate an NBO Instrument from a MicroMetaApp
JSON configuration and export it as NBO-XML.

Prerequisites:
-------------
1. Installation: The `inscoper_nbo` wheel must be installed in the active Python
   environment.
2. Sample Data: This script reads `micrometaapp_nikon_ti2.json`. Change
   MMA_JSON_PATH below to the location where you saved it, or to your own
   MicroMetaApp configuration.
"""

import os
import tempfile

import inscoper_nbo

# --8<-- [start:main_logic]
MMA_JSON_PATH = "micrometaapp_nikon_ti2.json"

# Step 1: Import the configuration
# fromMicroMetaAppJsonFile() parses the JSON produced by MicroMetaApp, maps every
# component to its NBO counterpart, and fills the instrument in a single call.
instrument = inscoper_nbo.Instrument()
instrument.fromMicroMetaAppJsonFile(MMA_JSON_PATH)

# A missing or unreadable file raises InscoperNBOException
try:
    inscoper_nbo.Instrument().fromMicroMetaAppJsonFile("does_not_exist.json")
except inscoper_nbo.InscoperNBOException as error:
    print(f"Import failed: {error}")

# Step 2: Inspect what the import produced
print(f"Instrument: {instrument.getID().get()}")

for stand in instrument.getMicroscopeStandGroup_List():
    print(f"Stand: {stand.getXMLName()} {stand.getManufacturer()} {stand.getModel()}")

for objective in instrument.getObjective_List():
    print(f"Objective: {objective.getModel()} - {objective.getMagnification()}x")

for detector in instrument.getDetectorGroup_List():
    print(f"Detector: {detector.getXMLName()} {detector.getModel()}")

for light_source in instrument.getLightSourceGroup_List():
    print(f"Light source: {light_source.getXMLName()} {light_source.getModel()}")

# Step 3: Export the imported instrument as NBO-XML
# Pass False to write exactly what the import produced, without validating the
# document and without filling in schema default values.
output_path = os.path.join(tempfile.gettempdir(), "instrument_from_mma.xml")
instrument.toXmlFile(output_path, False)
print(f"NBO-XML written to {output_path}")
# --8<-- [end:main_logic]
