import os
import pysera
from api.module import Module
from api.io_port import InPort, OutPort, NIFTIImageType, CSVTableType


def factory():
    m = Module("PySERAExtractor")

    in_image = InPort("image", NIFTIImageType())
    in_mask  = InPort("mask",  NIFTIImageType())

    out_features = OutPort("features", CSVTableType(columns=["name", "value"]))

    m.add_in_port(in_image)
    m.add_in_port(in_mask)
    m.add_out_port(out_features)

    def execute(inputs):
        image_input = inputs["image"]
        mask_input  = inputs["mask"]

        output_dir = "results"
        os.makedirs(output_dir, exist_ok=True)

        result = pysera.process_batch(
            image_input=image_input,
            mask_input=mask_input,
            output_path=output_dir,
            num_workers="auto",
            enable_parallelism=True,
            apply_preprocessing=True,
            categories="all",
            dimensions="1st,2_5d,3d",
            feature_value_mode="REAL_VALUE",
            extraction_mode="handcrafted_feature",
            report="info",
        )

        df = result.get("features_extracted")

        features = []
        if df is not None:
            for idx, row in df.iterrows():
                features.append({
                    "name": row[0],
                    "value": row[1]
                })

        return {
            "features": features
        }

    m.execute = execute
    return m
