##################################################################################
# This is a test program to validate that mmtbx.ribbons worked.
#

#                Copyright 2024  Richardson Lab at Duke University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import, division, print_function
from libtbx.utils import format_cpu_times
import os, subprocess, tempfile
import mmtbx
from mmtbx.programs import ribbons
import libtbx.load_env
from iotbx.cli_parser import run_program
from six.moves import cStringIO as StringIO
import re

def RunRibbonTests():

  #========================================================================
  # Regression test a against a snippet of a file, comparing the output
  # to the output generated by a previous version of the program.  If there are
  # differences, report that this is the case and recommend verifying that the
  # differences are intentional and replacing the stored output.
  data_dir = libtbx.env.under_dist(
    module_name = "mmtbx",
    path = os.path.join("regression","pdbs"),
    test = os.path.isdir)
  model_file = os.path.join(data_dir,'Fe_1brf_snip_reduced.pdb')
  temp_file = os.path.join(tempfile._get_default_tempdir(),
    next(tempfile._get_candidate_names())+".kin" )

  out = StringIO()
  try:
    # Run the program
    args = [model_file, "output.overwrite=True", 'output.filename='+temp_file]
    results = run_program(program_class=ribbons.Program, logger=out, args=args)

  except Exception as e:
    raise Exception("Could not call subprocess to do regression test: "+str(e))
  instructions = ("Use KiNG or another program to see what changed and then determine if the "+
      "differences are expected.  If so, modify the expected numbers of sheets and helices tested for.")

  # Count the number of helices and sheets in the output
  pattern = r"(\d+) helices and (\d+) sheets defined"
  match = re.search(pattern, out.getvalue())
  if match:
       N = int(match.group(1))
       S = int(match.group(2))
  else:
       raise Exception("Helix/sheet summary not found (printed by secondary structure manager)")

  if int(N) != 3 or int(S) != 1:
    raise Exception("Different number of helices ("+str(N)+" vs. 3) or sheets ("+str(S)+" vs. 1): "+instructions)

if __name__ == '__main__':

  RunRibbonTests()
  print(format_cpu_times())
  print('OK')
