/*
  This file is part of CDO. CDO is a collection of Operators to manipulate and analyse Climate model Data.

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Vertint    gh2hl           Model geometric height level to height level interpolation
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "field_vinterp.h"
#include "stdnametable.h"
#include "util_string.h"
#include "const.h"
#include "cdo_zaxis.h"
#include "param_conversion.h"
#include "vertint_util.h"

static bool
is_height_axis(int zaxisID)
{
  auto isHeight = false;
  if (zaxisInqType(zaxisID) == ZAXIS_REFERENCE)
    {
      char units[CDI_MAX_NAME], stdname[CDI_MAX_NAME];
      int length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_UNITS, units, &length);
      length = CDI_MAX_NAME;
      cdiInqKeyString(zaxisID, CDI_GLOBAL, CDI_KEY_STDNAME, stdname, &length);
      if (cdo_cmpstr(stdname, "height") && *units == 0) isHeight = true;
    }
  return isHeight;
}

static int
create_zaxis_height(Varray<double> &heightLevels)
{
  int zaxisID = CDI_UNDEFID;
  const auto &arg1 = cdo_operator_argv(0);
  if (cdo_operator_argc() == 1 && !isdigit(arg1[0]))
    {
      auto zfilename = arg1.c_str();
      auto zfp = fopen(zfilename, "r");
      if (zfp)
        {
          zaxisID = zaxis_from_file(zfp, zfilename);
          fclose(zfp);
          if (zaxisID == CDI_UNDEFID) cdo_abort("Invalid zaxis description file %s!", zfilename);
          const auto nlevels = zaxisInqSize(zaxisID);
          heightLevels.resize(nlevels);
          zaxisInqLevels(zaxisID, heightLevels.data());
        }
      else if (arg1 == "default")
        heightLevels = { 10, 50, 100, 500, 1000, 5000, 10000, 15000, 20000, 25000, 30000 };
      else
        cdo_abort("Open failed on %s", zfilename);
    }
  else
    {
      heightLevels = cdo_argv_to_flt(cdo_get_oper_argv());
    }

  if (zaxisID == CDI_UNDEFID)
    {
      zaxisID = zaxisCreate(ZAXIS_HEIGHT, heightLevels.size());
      zaxisDefLevels(zaxisID, heightLevels.data());
    }

  return zaxisID;
}

void *
Vertintgh(void *process)
{
  cdo_initialize(process);

  // clang-format off
                      cdo_operator_add("gh2hl",   0, 0, "height levels in meter");
  const auto GH2HLX = cdo_operator_add("gh2hlx",  0, 0, "height levels in meter");
  // clang-format on

  const auto operatorID = cdo_operator_id();

  auto extrapolate = (operatorID == GH2HLX);
  if (extrapolate == false) extrapolate = getenv_extrapolate();

  operator_input_arg(cdo_operator_enter(operatorID));

  Varray<double> heightLevels;
  const auto zaxisID2 = create_zaxis_height(heightLevels);

  const auto streamID1 = cdo_open_read(0);

  const auto vlistID1 = cdo_stream_inq_vlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto gridsize = vlist_check_gridsize(vlistID1);

  VarList varList1;
  varListInit(varList1, vlistID1);
  varListSetUniqueMemtype(varList1);
  const auto memtype = varList1[0].memType;

  const auto nvars = vlistNvars(vlistID1);

  char stdname[CDI_MAX_NAME];
  int fullHeightID = -1, halfHeightID = -1;

  for (int varID = 0; varID < nvars; varID++)
    {
      int length = CDI_MAX_NAME;
      cdiInqKeyString(vlistID1, varID, CDI_KEY_STDNAME, stdname, &length);
      cstr_to_lower_case(stdname);

      // clang-format off
      if (cdo_cmpstr(stdname, var_stdname(geometric_height_at_full_level_center))) fullHeightID = varID;
      if (cdo_cmpstr(stdname, var_stdname(geometric_height_at_half_level_center))) halfHeightID = varID;
      // clang-format on
    }

  if (Options::cdoVerbose)
    {
      cdo_print("Found:");
      // clang-format off
      if (-1 != fullHeightID) cdo_print("  %s -> %s", var_stdname(geometric_height_at_full_level_center), varList1[fullHeightID].name);
      if (-1 != halfHeightID) cdo_print("  %s -> %s", var_stdname(geometric_height_at_half_level_center), varList1[halfHeightID].name);
      // clang-format on
    }

  if (-1 == fullHeightID && -1 == halfHeightID) cdo_abort("%s not found!", var_stdname(geometric_height_at_full_level_center));

  const auto zaxisIDfull = (-1 == fullHeightID) ? -1 : varList1[fullHeightID].zaxisID;
  const auto zaxisIDhalf = (-1 == halfHeightID) ? -1 : varList1[halfHeightID].zaxisID;
  const auto numFullLevels = (-1 == zaxisIDfull) ? 0 : zaxisInqSize(zaxisIDfull);
  const auto numHalfLevels = (-1 == zaxisIDhalf) ? 0 : zaxisInqSize(zaxisIDhalf);

  const auto nzaxis = vlistNzaxis(vlistID1);
  for (int index = 0; index < nzaxis; index++)
    {
      const auto zaxisID = vlistZaxis(vlistID1, index);
      const auto nlevels = zaxisInqSize(zaxisID);
      if (zaxisID == zaxisIDfull || zaxisID == zaxisIDhalf
          || (is_height_axis(zaxisID) && (nlevels == numHalfLevels || nlevels == numFullLevels)))
        vlistChangeZaxis(vlistID2, zaxisID, zaxisID2);
    }

  VarList varList2;
  varListInit(varList2, vlistID2);
  varListSetMemtype(varList2, memtype);

  Field heightBottom;

  Varray<size_t> pnmiss;
  if (!extrapolate) pnmiss.resize(heightLevels.size());

  std::vector<int> vertIndexFull, vertIndexHalf;
  if (-1 != fullHeightID) vertIndexFull.resize(gridsize * heightLevels.size());
  if (-1 != halfHeightID) vertIndexHalf.resize(gridsize * heightLevels.size());

  std::vector<bool> vars(nvars), varinterp(nvars);
  Varray2D<size_t> varnmiss(nvars);
  Field3DVector vardata1(nvars), vardata2(nvars);

  const auto maxlev = std::max(std::max(numFullLevels, numHalfLevels), (int) heightLevels.size());

  for (int varID = 0; varID < nvars; varID++)
    {
      const auto gridID = varList1[varID].gridID;
      const auto zaxisID = varList1[varID].zaxisID;
      const auto nlevels = varList1[varID].nlevels;

      if (gridInqType(gridID) == GRID_SPECTRAL) cdo_abort("Spectral data unsupported!");

      vardata1[varID].init(varList1[varID]);

      varinterp[varID] = (zaxisID == zaxisIDfull || zaxisID == zaxisIDhalf
                          || (is_height_axis(zaxisID) && (nlevels == numHalfLevels || nlevels == numFullLevels)));

      if (varinterp[varID])
        {
          varnmiss[varID].resize(maxlev, 0);
          vardata2[varID].init(varList2[varID]);
        }
      else
        {
          if (is_height_axis(zaxisID) && nlevels > 1)
            {
              if (-1 == fullHeightID && -1 != halfHeightID && nlevels == (numHalfLevels - 1))
                cdo_abort("%s not found (needed for %s)!", var_stdname(geometric_height_at_full_level_center),
                          varList1[varID].name);
              else if (-1 != fullHeightID && -1 == halfHeightID && nlevels == (numFullLevels + 1))
                cdo_abort("%s not found (needed for %s)!", var_stdname(geometric_height_at_half_level_center),
                          varList1[varID].name);
              else
                cdo_warning("Parameter %d has wrong number of levels, skipped! (name=%s nlevel=%d)", varID + 1,
                            varList1[varID].name, nlevels);
            }
          varnmiss[varID].resize(nlevels);
        }
    }

  for (int varID = 0; varID < nvars; ++varID)
    {
      if (varinterp[varID] && varList1[varID].timetype == TIME_CONSTANT) vlistDefVarTimetype(vlistID2, varID, TIME_VARYING);
    }

  const auto streamID2 = cdo_open_write(1);

  cdo_def_vlist(streamID2, vlistID2);

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      for (int varID = 0; varID < nvars; ++varID)
        {
          vars[varID] = false;
          const auto nlevels = varList1[varID].nlevels;
          for (int levelID = 0; levelID < nlevels; levelID++) varnmiss[varID][levelID] = 0;
        }

      cdo_taxis_copy_timestep(taxisID2, taxisID1);
      cdo_def_timestep(streamID2, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          cdo_read_record(streamID1, vardata1[varID], levelID, &varnmiss[varID][levelID]);
          vars[varID] = true;
        }

      for (int varID = 0; varID < nvars; varID++)
        if (varinterp[varID]) vars[varID] = true;

      auto lreverse = true;
      if (-1 != fullHeightID && (tsID == 0 || varList1[fullHeightID].timetype != TIME_CONSTANT))
        {
          gen_vert_index(vertIndexFull, heightLevels, vardata1[fullHeightID], gridsize, lreverse);
          if (!extrapolate)
            {
              heightBottom.init(varList1[fullHeightID]);
              field_copy(vardata1[fullHeightID], numFullLevels - 1, heightBottom);
              gen_vert_index_mv(vertIndexFull, heightLevels, gridsize, heightBottom, pnmiss, lreverse);
            }
        }

      if (-1 != halfHeightID && (tsID == 0 || varList1[halfHeightID].timetype != TIME_CONSTANT))
        {
          gen_vert_index(vertIndexHalf, heightLevels, vardata1[halfHeightID], gridsize, lreverse);
          if (!extrapolate)
            {
              heightBottom.init(varList1[halfHeightID]);
              field_copy(vardata1[halfHeightID], numHalfLevels - 1, heightBottom);
              gen_vert_index_mv(vertIndexHalf, heightLevels, gridsize, heightBottom, pnmiss, lreverse);
            }
        }

      for (int varID = 0; varID < nvars; varID++)
        {
          if (vars[varID])
            {
              if (tsID > 0 && !varinterp[varID] && varList1[varID].timetype == TIME_CONSTANT) continue;

              if (varinterp[varID])
                {
                  const auto nlevels = varList1[varID].nlevels;
                  if (nlevels != numFullLevels && nlevels != numHalfLevels)
                    cdo_abort("Number of generalized height level differ from full/half level (param=%s)!", varList1[varID].name);

                  for (int levelID = 0; levelID < nlevels; levelID++)
                    {
                      if (varnmiss[varID][levelID]) cdo_abort("Missing values unsupported for this operator!");
                    }

                  if (nlevels == numFullLevels)
                    vertical_interp_X(nlevels, vardata1[fullHeightID], vardata1[varID], vardata2[varID], vertIndexFull,
                                      heightLevels, gridsize);
                  else
                    vertical_interp_X(nlevels, vardata1[halfHeightID], vardata1[varID], vardata2[varID], vertIndexHalf,
                                      heightLevels, gridsize);

                  if (!extrapolate) varray_copy(heightLevels.size(), pnmiss, varnmiss[varID]);
                }

              for (int levelID = 0; levelID < varList2[varID].nlevels; levelID++)
                {
                  cdo_def_record(streamID2, varID, levelID);
                  cdo_write_record(streamID2, varinterp[varID] ? vardata2[varID] : vardata1[varID], levelID,
                                   varnmiss[varID][levelID]);
                }
            }
        }

      tsID++;
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
