#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 26 17:04:36 2026

@author: blissadm
"""

import os

import h5py
from ewokscore import Task
from pyicat_plus.metadata.drac_report_builder import DracReportBuilder
from silx.io import h5py_utils
from silx.io.url import DataUrl

DEFAULTS = {}


class SumfitSummaryReport(
    Task,
    input_names=["output_root_uri", "bliss_scan_uri"],
    optional_input_names=[],
    output_names=["output_root_uri", "bliss_scan_uri"],
):
    """Generate a report of sumfit tasks for the data portal"""

    def run(self):

        pars = {**DEFAULTS, **self.get_input_values()}

        # From https://pyicat-plus.readthedocs.io/en/stable/other_features.html#drac-report-builder

        output_root_uri = DataUrl(pars["output_root_uri"])
        gallery_path = os.path.join(
            os.path.dirname(output_root_uri.file_path()), "gallery"
        )

        fitting_results = {}
        detectors = set()

        with h5py_utils.open_item(
            output_root_uri.file_path(), output_root_uri.data_path()
        ) as scan:
            for k in scan:

                if isinstance(scan[k], h5py.Group) and "sumfit" in scan[k]:
                    detectors.add(k)
                    fitgrp = scan[k]["sumfit"]
                    for elm in fitgrp["areal_density"]:

                        if elm not in fitting_results:
                            fitting_results[elm] = {}

                        fitting_results[elm][k] = (
                            fitgrp["areal_density"][elm][()],
                            fitgrp["fitarea"][elm][()],
                        )

        table_results = []
        table_title = ["Element"]

        for d in detectors:
            table_title += [
                f"{d} fit area",
                f"{d} areal density (ng/mm2)",
            ]

        if len(detectors) > 1:
            table_title += ["Total fit area", "Average areal density (ng/mmg2)"]

        for elm, v in fitting_results.items():
            area = 0.0
            prod = 0.0

            row = [
                elm,
            ]

            for d in detectors:
                vals = v.get(d, None)

                if vals is None:
                    row += ["N/A", "N/A"]
                else:
                    area += vals[1]
                    prod += vals[0] * vals[1]

                    row += [f"{vals[1]:.5g}", f"{vals[0]:.5g}"]

            if len(detectors) > 1:
                weighted = prod / area
                row += [f"{area:.5g}", f"{weighted:.5g}"]

            table_results += [
                row,
            ]

        # Create report
        report = DracReportBuilder(
            dataset_type="xrf_fitting",
            dataset_title="XRF fitting report",
        )

        # Add text elements
        #        report.add_info("This is a demo info item.")
        #        report.add_warning("Warning !")

        # Add a row of images (must be inside an image list)
        report.start_image_list()

        for d in detectors:
            filepath = os.path.join(gallery_path, f"{d}_sumfit.jpg")
            if os.path.isfile(filepath):

                report.add_image(
                    path_to_image=filepath,
                    image_title=f"{d} sumfit",
                    thumbnail_height=200,
                )

        report.end_image_list()

        # Add a table
        report.add_table(
            title="Fitting results",
            columns=table_title,
            data=table_results,
            orientation="vertical",
        )

        # Export DRAC JSON
        report.render_json(
            path_to_json_dir=gallery_path,
        )

        self.outputs.output_root_uri = pars["output_root_uri"]
        self.outputs.bliss_scan_uri = pars["bliss_scan_uri"]
