# Copyright (C) 2021 - 2026 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Meshing workflow specialization of the Workflow module that wraps and extends the
core functionality."""

from __future__ import annotations

from enum import Enum
import os

from ansys.fluent.core._types import PathType
from ansys.fluent.core.services.datamodel_se import PyMenuGeneric
from ansys.fluent.core.utils.fluent_version import FluentVersion
from ansys.fluent.core.workflow_new import Workflow


class MeshingWorkflow(Workflow):
    """Provides meshing specialization of the workflow wrapper that extends the core
    functionality in an object-oriented manner."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        name: str,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize MeshingWorkflow.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        name: str
            Workflow name to initialize it.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow, command_source=meshing, fluent_version=fluent_version
        )
        self._meshing = meshing
        self._name = name
        if initialize:
            self._new_workflow(name=self._name)
        self._initialized = True


class WatertightMeshingWorkflow(MeshingWorkflow):
    """Provides watertight meshing specialization of the workflow wrapper."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize WatertightMeshingWorkflow.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow,
            meshing=meshing,
            name="Watertight Geometry",
            fluent_version=fluent_version,
            initialize=initialize,
        )


class FaultTolerantMeshingWorkflow(MeshingWorkflow):
    """Provides fault-tolerant meshing specialization of the workflow wrapper."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        part_management: PyMenuGeneric,
        pm_file_management: PyMenuGeneric,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize FaultTolerantMeshingWorkflow.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        part_management : PyMenuGeneric
            Part management object.
        pm_file_management : PyMenuGeneric
            File management object in the part management object.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow,
            meshing=meshing,
            name="Fault-tolerant Meshing",
            fluent_version=fluent_version,
            initialize=initialize,
        )
        self._parent_workflow = workflow
        self._part_management = part_management
        self._pm_file_management = pm_file_management

    @property
    def parts(self) -> PyMenuGeneric | None:
        """Access part-management in fault-tolerant mode.

        Returns
        -------
        PyMenuGeneric | None
            Part-management.
        """
        return self._parent_workflow.parts

    @property
    def parts_files(self):
        """Access the part-management file-management object in fault-tolerant mode.

        Returns
        -------
        PyMenuGeneric | None
            File management object in the part management object.
        """
        return self._parent_workflow.parts_files

    @property
    def part_management(self) -> PyMenuGeneric | None:
        """Access part-management in fault-tolerant mode.

        Returns
        -------
        PyMenuGeneric | None
            Part-management.
        """
        # TODO: Remove this after migrating to the new workflow
        return self._part_management

    @property
    def pm_file_management(self):
        """Access the part-management file-management object in fault-tolerant mode.

        Returns
        -------
        PyMenuGeneric | None
            File management object in the part management object.
        """
        # TODO: Remove this after migrating to the new workflow
        return self._pm_file_management


class TwoDimensionalMeshingWorkflow(MeshingWorkflow):
    """Provides 2D meshing specialization of the workflow wrapper."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize TwoDimensionalMeshingWorkflow.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow,
            meshing=meshing,
            name="2D Meshing",
            fluent_version=fluent_version,
            initialize=initialize,
        )


class TopologyBasedMeshingWorkflow(MeshingWorkflow):
    """Provides topology-based meshing specialization of the workflow wrapper."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize TopologyBasedMeshingWorkflow.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow,
            meshing=meshing,
            name="Topology Based Meshing",
            fluent_version=fluent_version,
            initialize=initialize,
        )


class WorkflowMode(Enum):
    """Provides an enum of supported Fluent meshing workflow modes."""

    WATERTIGHT_MESHING_MODE = WatertightMeshingWorkflow
    FAULT_TOLERANT_MESHING_MODE = FaultTolerantMeshingWorkflow
    TWO_DIMENSIONAL_MESHING_MODE = TwoDimensionalMeshingWorkflow
    TOPOLOGY_BASED_MESHING_MODE = TopologyBasedMeshingWorkflow


class LoadWorkflow(Workflow):
    """Provides a specialization of the workflow wrapper for a loaded workflow."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        fluent_version: FluentVersion,
        file_path: PathType = None,
        initialize: bool = True,
    ) -> None:
        """Initialize a ``LoadWorkflow`` instance.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        file_path: os.PathLike[str | bytes] | str | bytes
            Path to the saved workflow file.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow, command_source=meshing, fluent_version=fluent_version
        )
        self._meshing = meshing
        if initialize:
            self._load_workflow(file_path=os.fspath(file_path))


class CreateWorkflow(Workflow):
    """Provides a specialization of the workflow wrapper for a newly created
    workflow."""

    def __init__(
        self,
        workflow: PyMenuGeneric,
        meshing: PyMenuGeneric,
        fluent_version: FluentVersion,
        initialize: bool = True,
    ) -> None:
        """Initialize a ``CreateWorkflow`` instance.

        Parameters
        ----------
        workflow : PyMenuGeneric
            Underlying workflow object.
        meshing : PyMenuGeneric
            Meshing object.
        fluent_version: FluentVersion
            Version of Fluent in this session.
        initialize: bool
            Flag to initialize the workflow, defaults to True.
        """
        super().__init__(
            workflow=workflow, command_source=meshing, fluent_version=fluent_version
        )
        self._meshing = meshing
        if initialize:
            self._create_workflow()


def _get_current_workflow(current_workflow, name: str):
    if current_workflow and current_workflow._name == name:
        return current_workflow


def get_current_workflow(
    workflow_root, current_workflow, workflow_factories, load_workflow_handle
) -> Workflow:
    """Get the currently active workflow in new mode.

    Parameters
    ----------
    workflow_root : PyMenuGeneric
        Root workflow datamodel object.
    current_workflow : Workflow or None
        Currently cached workflow instance.
    workflow_factories : dict
        Mapping of workflow type names to factory functions.
    load_workflow_handle : callable
        Function to load a workflow from file.

    Returns
    -------
    Workflow
        The currently active workflow instance.

    Raises
    ------
    RuntimeError
        If no workflow is initialized.
    """
    # New mode: Check workflow type from meshing_workflow datamodel
    workflow_type = workflow_root.general.workflow.workflow_type()

    # Check if no workflow is initialized
    if workflow_type in ["Select Workflow Type", None]:
        raise RuntimeError("No workflow initialized.")

    # Handle loaded workflows (not in the factory map)
    if workflow_type not in workflow_factories:
        # This is a loaded workflow
        if current_workflow and current_workflow.__class__.__name__ == "LoadWorkflow":
            return current_workflow
        return load_workflow_handle(initialize=False)

    # Get or create workflow based on type
    factory = workflow_factories[workflow_type]
    return _get_current_workflow(current_workflow, workflow_type) or factory(
        initialize=False
    )
