/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | Multiphase Code Repository by HZDR
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.767
  ||  ||  //    ||  // || \\   | License: GPL-3.0-or-later
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
License
    This file is part of the Multiphase Code Repository by HZDR.

    Copyright (C) 2025 by Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR),
    Website: https://hzdr.de

    Multiphase Code Repository by HZDR is based on the free software for
    computational fluid dynamics (CFD) from the OpenFOAM Foundation.
    Copyright (C) 2025 by OpenFOAM Foundation, Website: https://openfoam.org

    If you are interested in which files are original OpenFOAM Foundation
    files, which OpenFOAM Foundation files were modified, and which files were
    newly created, see FILES.md.

    Multiphase Code Repository by HZDR is free software: you can redistribute
    it and/or modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    Multiphase Code Repository by HZDR is distributed in the hope that it will
    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
    Public License for more details.

    You should have received a copy of the GNU General Public License along
    with the Multiphase Code Repository by HZDR. If not, see
    <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "resolvedInterfaceSystem.H"

#include "interfaceCompressionModel.H"
#include "surfaceTensionForceModel.H"
#include "subGridSurfaceTensionModel.H"
#include "interfaceIndicatorMethod.H"
#include "underResolutionModel.H"
#include "clusterTrackingModel.H"
#include "moveAlphaByPotentialModel.H"
#include "generateInterfacialModels.H"

#include "fvcGrad.H"
#include "fvcSnGrad.H"
#include "fvcFlux.H"

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
    defineTypeNameAndDebug(resolvedInterfaceSystem, 0);
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::resolvedInterfaceSystem::resolvedInterfaceSystem(const phaseSystem& fluid)
:
    regIOobject
    (
        IOobject
        (
            "resolvedInterface",
            fluid.mesh().time().name(),
            fluid.mesh(),
            IOobject::NO_READ,
            IOobject::NO_WRITE
        )
    ),
    fluid_(fluid),
    interfaceCompressionModels_
    (
        fluid_.found("interfaceCompression")
      ? generateInterfacialModels<interfaceCompressionModel>
        (
            fluid_,
            fluid_.subDict(modelName<interfaceCompressionModel>())
        )
      : interfaceCompressionModelTable()
    ),
    surfaceTensionForceModel_(surfaceTensionForceModel::New(*this)),
    subGridSurfaceTensionModels_
    (
        fluid_.found("subGridSurfaceTension")
      ? generateInterfacialModels<subGridSurfaceTensionModel>
        (
            fluid_,
            fluid_.subDict(modelName<subGridSurfaceTensionModel>())
        )
      : subGridSurfaceTensionModelTable()
    ),
    interfaceIndicatorMethod_(interfaceIndicatorMethod::New(*this)),
    underResolutionModels_
    (
        fluid_.found("underResolution")
      ? generateInterfacialModels<underResolutionModel>
        (
            fluid_,
            fluid_.subDict(modelName<underResolutionModel>())
        )
      : underResolutionModelTable()
    ),

    clusterTrackingModels_
    (
        fluid_.found("clusterTracking")
      ? generateInterfacialModels<clusterTrackingModel>
        (
            fluid_,
            fluid_.subDict(modelName<clusterTrackingModel>())
        )
      : clusterTrackingModelTable()
    ),

    moveAlphaByPotentialModels_
    (
        fluid_.found("moveAlphaByPotential")
      ? generateInterfacialModels<moveAlphaByPotentialModel>
        (
            fluid_,
            fluid_.subDict(modelName<moveAlphaByPotentialModel>())
        )
      : moveAlphaByPotentialModelTable()
    )
{
    // Groupings
    label continuousPhasei = 0;

    forAll(fluid_.movingPhases(), phasei)
    {
        const phaseModel& movingPhase = fluid_.movingPhases()[phasei];
        continuousPhasei += movingPhase.continuous();
    }

    continuousPhaseModels_.resize(continuousPhasei);

    continuousPhasei = 0;

    forAll(fluid_.movingPhases(), phasei)
    {
        phaseModel& movingPhase =
            const_cast<phaseModel&>(fluid_.movingPhases()[phasei]);

        if (movingPhase.continuous())
        {
            continuousPhaseModels_.set(continuousPhasei++, &movingPhase);
        }
    }

    if (!continuousPhaseModels_.empty())
    {
        Info<< "Continuous phases:";
        forAll(continuousPhaseModels_, phasei)
        {
            Info<< " " << continuousPhaseModels_[phasei].name();
        }
        Info<< endl;
    }
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::resolvedInterfaceSystem::~resolvedInterfaceSystem()
{}


// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //

void
Foam::resolvedInterfaceSystem::addCompressionFlux
(
    const phaseModel& phase,
    surfaceScalarField& alphaPhi
) const
{
    if (!interfaceCompressionModels_.empty())
    {
        const volScalarField& alpha = phase;

        forAll(fluid_.phases(), phasei)
        {
            const phaseModel& phase2 = fluid_.phases()[phasei];
            const volScalarField& alpha2 = phase2;
            const phaseInterfaceKey key(phase, phase2);

            if (&phase2 == &phase) continue;

            interfaceCompressionModelTable::const_iterator cAlpha
            (
                interfaceCompressionModels_.find(key)
            );

            if (cAlpha != interfaceCompressionModels_.end())
            {
                const surfaceScalarField phirc
                (
                    interfaceCompressionModels_[key]->phirc(phase)
                );

                const word phirScheme
                (
                    "div(phir,"
                  + alpha2.name() + ',' + alpha.name()
                  + ')'
                );

                alphaPhi += fvc::flux
                (
                    -fvc::flux(-phirc, alpha2, phirScheme),
                    alpha,
                    phirScheme
                );
            }
        }
    }

    if (!moveAlphaByPotentialModels_.empty())
    {
        const volScalarField& alpha = phase;

        forAll(fluid_.phases(), phasei)
        {
            const phaseModel& phase2 = fluid_.phases()[phasei];
            const volScalarField& alpha2 = phase2;
            const phaseInterfaceKey key(phase, phase2);

            if (&phase2 == &phase) continue;

            moveAlphaByPotentialModelTable::const_iterator cAlpha
            (
                moveAlphaByPotentialModels_.find(key)
            );

            if (cAlpha != moveAlphaByPotentialModels_.end())
            {
                const surfaceScalarField phir
                (
                    moveAlphaByPotentialModels_[key]->phirc(phase)
                );

                const word phirScheme
                (
                    "div(phir,"
                  + alpha2.name() + ',' + alpha.name()
                  + ')'
                );

                alphaPhi += fvc::flux
                (
                    -fvc::flux(-phir, alpha2, phirScheme),
                    alpha,
                    phirScheme
                );
            }
        }
    }
}


Foam::tmp<Foam::surfaceScalarField>
Foam::resolvedInterfaceSystem::surfaceTension(const phaseModel& phase1) const
{
    tmp<surfaceScalarField> tSurfaceTension
    (
        new surfaceScalarField
        (
            IOobject
            (
                "surfaceTension",
                this->mesh().time().name(),
                this->mesh()
            ),
            this->mesh(),
            dimensionedScalar
            (
                "surfaceTension",
                dimensionSet(1, -2, -2, 0, 0),
                0
            )
        )
    );

    forAll(fluid_.phases(), phasej)
    {
        const phaseModel& phase2 = fluid_.phases()[phasej];

        if (&phase2 == &phase1) continue;

        const phaseInterfaceKey key(phase1, phase2);

        if (interfaceCompressionModels_.found(key))
        {
            if (interfaceCompressionModels_[key]->type() != "none")
            {
                const segregatedPhaseInterface interface(phase1, phase2);

                tSurfaceTension.ref() +=
                    surfaceTensionForceModel_->surfaceTensionForcef(interface);

                if (subGridSurfaceTensionModels_.found(key))
                {
                    if
                    (
                        subGridSurfaceTensionModels_[key]->type()
                        != "none"
                    )
                    {
                        tSurfaceTension.ref() +=
                            subGridSurfaceTensionModels_[key]->
                            subGridSurfaceTensionForcef();
                    }
                }
            }
        }
    }

    return tSurfaceTension;
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::interfaceIndicator(const phaseModel& phase) const
{
   return interfaceIndicatorMethod_->interfaceIndicator(phase);
}


Foam::tmp<Foam::volVectorField>
Foam::resolvedInterfaceSystem::gradAlpha
(
    const volScalarField& alpha1,
    const volScalarField& alpha2
) const
{
    return alpha2*fvc::grad(alpha1) - alpha1*fvc::grad(alpha2);
}


Foam::tmp<Foam::surfaceScalarField>
Foam::resolvedInterfaceSystem::gradAlphaf
(
    const volScalarField& alpha1,
    const volScalarField& alpha2
) const
{
    return
        fvc::interpolate(alpha2)*fvc::snGrad(alpha1)
      - fvc::interpolate(alpha1)*fvc::snGrad(alpha2);
}


Foam::tmp<Foam::volVectorField>
Foam::resolvedInterfaceSystem::gradAlphaI(const phaseInterfaceKey& key) const
{
    if (underResolutionModels_.found(key))
    {
        return underResolutionModels_[key]->gradAlphaI();
    }
    else
    {
        FatalErrorInFunction
            << "Requesting gradAlphaI from phase interface "
            << phaseInterface(fluid_, key).name()
            << ", underResolutionModel not found." << endl;

        return tmp<volVectorField>(nullptr);
    }
}


Foam::tmp<Foam::volVectorField>
Foam::resolvedInterfaceSystem::nHat
(
    const volScalarField& alpha1,
    const volScalarField& alpha2
) const
{
    const volVectorField tgradAlpha(gradAlpha(alpha1, alpha2));

    return tgradAlpha/(mag(tgradAlpha) + fluid_.deltaN());
}


Foam::tmp<Foam::surfaceVectorField>
Foam::resolvedInterfaceSystem::nHatfv
(
    const volScalarField& alpha1,
    const volScalarField& alpha2
) const
{
    /*
    // Cell gradient of alpha
    volVectorField gradAlpha =
        alpha2*fvc::grad(alpha1) - alpha1*fvc::grad(alpha2);

    // Interpolated face-gradient of alpha
    surfaceVectorField gradAlphaf = fvc::interpolate(gradAlpha);
    */

    surfaceVectorField gradAlphaf
    (
        fvc::interpolate(alpha2)*fvc::interpolate(fvc::grad(alpha1))
      - fvc::interpolate(alpha1)*fvc::interpolate(fvc::grad(alpha2))
    );

    // Face unit interface normal
    return gradAlphaf/(mag(gradAlphaf) + fluid_.deltaN());
}


Foam::tmp<Foam::surfaceScalarField>
Foam::resolvedInterfaceSystem::nHatf
(
    const volScalarField& alpha1,
    const volScalarField& alpha2
) const
{
    // Face unit interface normal flux
    return nHatfv(alpha1, alpha2) & fluid_.mesh().Sf();
}


Foam::tmp<Foam::volVectorField>
Foam::resolvedInterfaceSystem::UrI(const phaseInterfaceKey& key) const
{
    if (underResolutionModels_.found(key))
    {
        return underResolutionModels_[key]->UrI();
    }
    else
    {
        FatalErrorInFunction
            << "Requesting UrI from phase interface "
            << phaseInterface(fluid_, key).name()
            << ", underResolutionModel not found." << endl;

        return tmp<volVectorField>(nullptr);
    }
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::tauI(const phaseInterfaceKey& key) const
{
    if (underResolutionModels_.found(key))
    {
        return underResolutionModels_[key]->tauI();
    }
    else
    {
        FatalErrorInFunction
            << "Requesting tauI from phase interface "
            << phaseInterface(fluid_, key).name()
            << ", underResolutionModel not found." << endl;

        return tmp<volScalarField>(nullptr);
    }
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::K
(
    const segregatedPhaseInterface& interface
) const
{
    return surfaceTensionForceModel_->K(interface);
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::underResolution
(
    const phaseInterfaceKey& key
) const
{
    if (underResolutionModels_.found(key))
    {
        return underResolutionModels_[key]->underResolution();
    }
    else
    {
        FatalErrorInFunction
            << "Requesting underResolution from phase interface "
            << phaseInterface(fluid_, key).name()
            << ", underResolutionModel not found." << endl;

        return tmp<volScalarField>(nullptr);
    }
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::underResolution(const phaseModel& phase) const
{
    // Consider only interfaces between continuous phases
    if (!phase.continuous())
    {
        FatalErrorInFunction
            << "Attempt to determine under-resolution for non-continuous "
            << "phase: " << phase.name() << endl
            << exit(FatalError);
    }

    tmp<volScalarField> tUnderResolution
    (
        new volScalarField
        (
            IOobject
            (
                "underResolution",
                mesh().time().name(),
                mesh()
            ),
            mesh(),
            dimensionedScalar("underResolution", dimless, 0)
        )
    );

    forAll(fluid_.phases(), phasej)
    {
        const phaseModel& phase2 = fluid_.phases()[phasej];

        if (&phase2 == &phase || !phase2.continuous()) continue;

        const phaseInterfaceKey key(phase, phase2);

        if (underResolutionModels_.found(key))
        {
            tUnderResolution.ref() =
                max
                (
                    underResolutionModels_[key]->underResolution(),
                    tUnderResolution.ref()
                );
        }
    }

    return tUnderResolution;
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::rhoContinuous() const
{
    const phaseSystem::phaseModelPartialList& movingPhases =
        fluid_.movingPhases();

    const label nPhases = movingPhases.size();

    tmp<volScalarField> rhoCont
    (
        movingPhases[0].continuous()
       *movingPhases[0]
       *movingPhases[0].rho()
    );

    for (label phasei = 1; phasei < nPhases; ++phasei)
    {
        rhoCont.ref() +=
            movingPhases[phasei].continuous()
           *movingPhases[phasei]
           *movingPhases[phasei].rho();
    }

    return rhoCont/max(sumAlphaContinuous(), small);
}


Foam::tmp<Foam::volScalarField>
Foam::resolvedInterfaceSystem::sumAlphaContinuous() const
{
    if (continuousPhaseModels_.size())
    {
        tmp<volScalarField> sumAlphaContinuous
        (
            volScalarField::New
            (
                "sumAlphaContinuous",
                continuousPhaseModels_[0],
                calculatedFvPatchScalarField::typeName
            )
        );

        for
        (
            label continuousPhasei=1;
            continuousPhasei<continuousPhaseModels_.size();
            continuousPhasei++
        )
        {
            sumAlphaContinuous.ref() +=
                continuousPhaseModels_[continuousPhasei];
        }

        return sumAlphaContinuous;
    }
    else
    {
        return
            tmp<volScalarField>
            (
                volScalarField::New
                (
                    "sumAlphaContinuous",
                    fluid_.mesh(),
                    0
                )
            );
    }
}


void Foam::resolvedInterfaceSystem::solve()
{
    // Conversion of large fluid particles to resolved state
    if (clusterTrackingModels_.size())
    {
        // Count active cluster tracking pairs
        label activeTrackings(0);
        forAllIter
        (
            clusterTrackingModelTable,
            clusterTrackingModels_,
            clusterTrackingModelIter
        )
        {
            activeTrackings += clusterTrackingModelIter()->isActive();
        }

        // Process one at a time
        if (activeTrackings == 1)
        {
            forAllIter
            (
                clusterTrackingModelTable,
                clusterTrackingModels_,
                clusterTrackingModelIter
            )
            {
                if (clusterTrackingModelIter()->isActive())
                {
                    clusterTrackingModelIter()->updateClusters();
                }
            }
        }
        else // Identify phase interface with largest over-resolved diameter
        {
            Info<< "Cluster tracking: Find candidate" << endl;
            scalar largestDiameter(0);
            phaseInterfaceKey candidateKey;

            forAllIter
            (
                clusterTrackingModelTable,
                clusterTrackingModels_,
                clusterTrackingModelIter
            )
            {
                // Update all clustering pairs and find largest diameter among
                // active ones
                if
                (
                    clusterTrackingModelIter()->updateClusters()
                && clusterTrackingModelIter()->diameter() > largestDiameter
                )
                {
                    largestDiameter = clusterTrackingModelIter()->diameter();
                    candidateKey = clusterTrackingModelIter()->key();
                }
            }

            // Keep only identified phase interface active
            forAllIter
            (
                clusterTrackingModelTable,
                clusterTrackingModels_,
                clusterTrackingModelIter
            )
            {
                if
                (
                    largestDiameter
                && (clusterTrackingModelIter()->key() == candidateKey)
                )
                {
                    Info<< "Cluster tracking: Keep "
                        << clusterTrackingModelIter()->compressedPhase().name()
                        << endl;
                }
                else
                {
                    clusterTrackingModelIter()->discard();
                }
            }
        }
    }
}


void Foam::resolvedInterfaceSystem::correct()
{
    forAllConstIter
    (
        underResolutionModelTable,
        underResolutionModels_,
        underResolutionModelIter
    )
    {
        underResolutionModelIter()->correct();
    }
}


bool Foam::resolvedInterfaceSystem::writeData(Ostream& os) const
{
    return os.good();
}


// ************************************************************************* //
