import json
import os
from typing import Any
from typing import Dict
from typing import List
from typing import Optional

from ...bliss_globals import current_session
from ...bliss_globals import setup_globals
from ...id22.xrpd_processor import Id22XrpdProcessor
from ...utils import directories
from ..processors.utils.pyfai_calib import DEFAULT_CALIB
from ..processors.utils.xrpd import lima_image_is_padded


class DemoId22XrpdProcessor(Id22XrpdProcessor):
    def __init__(
        self,
        config: Optional[Dict[str, Any]] = None,
        defaults: Optional[Dict[str, Any]] = None,
        **deprecated_defaults: Dict[str, Any],
    ) -> None:
        defaults = self._merge_defaults(deprecated_defaults, defaults)

        defaults.setdefault("queue", "celery")
        defaults.setdefault(
            "integration_options",
            {
                "method": "no_csr_cython",
                "nbpt_rad": 4096,
                "unit": "q_nm^-1",
            },
        )

        super().__init__(config=config, defaults=defaults)
        if self._HAS_BLISS:
            self._ensure_config_filename()

    def get_integrate_1d_inputs(self, scan, lima_name: str) -> List[dict]:
        inputs = super().get_integrate_1d_inputs(scan, lima_name)
        inputs.append(
            {
                "task_identifier": "Integrate1D",
                "name": "demo",
                "value": lima_image_is_padded(lima_name),
            }
        )
        return inputs

    def _get_demo_result_dir(self, dataset_filename: str) -> str:
        root_dir = directories.get_processed_dir(dataset_filename)
        return os.path.join(root_dir, "demo", "id22")

    def _get_workflows_dir(self, dataset_filename: str) -> str:
        root_dir = self._get_demo_result_dir(dataset_filename)
        return os.path.join(root_dir, "workflows")

    def _get_config_dir(self, dataset_filename: str) -> str:
        root_dir = self._get_demo_result_dir(dataset_filename)
        return os.path.join(root_dir, "config")

    def _ensure_config_filename(self):
        if self.pyfai_config:
            return
        root_dir = self._get_config_dir(current_session.scan_saving.filename)
        cfgfile = os.path.join(root_dir, "pyfaicalib.json")
        os.makedirs(os.path.dirname(cfgfile), exist_ok=True)
        poni = DEFAULT_CALIB["difflab6"]
        with open(cfgfile, "w") as f:
            json.dump(poni, f)
        self.pyfai_config = cfgfile

    def pct(self, *args, **kw):
        s = setup_globals.ct(*args, **kw)
        self.on_new_scan(s)
        return s

    def _expected_data_shapes_1d(self, lima_name: str, npoints: int):
        return {
            f"{lima_name}:q": (4096,),
            f"{lima_name}:intensity": (4096,),
            f"{lima_name}:intensity_errors": (4096,),
        }
