/*
    libmaus2
    Copyright (C) 2021 German Tischler-Höhle

    This program 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.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <libmaus2/parallel/threadpool/cram/ThreadPoolCramEnqueueControl.hpp>
#include <libmaus2/util/ArgParser.hpp>
#include <libmaus2/aio/StreamLock.hpp>
#include <libmaus2/util/GetFileSize.hpp>
#include <libmaus2/parallel/NumCpus.hpp>
#include <regex>
#include <filesystem>
#include <libmaus2/fastx/FastAReader.hpp>
#include <libmaus2/digest/md5.hpp>

int main(int argc, char * argv[])
{
	try
	{
		libmaus2::util::ArgParser arg(argc,argv);

		if ( ! arg.uniqueArgPresent("r") )
		{
			std::cerr << "[E] argument -r (reference) missing" << std::endl;
			return EXIT_FAILURE;
		}

		std::string const ref = arg["r"];

		std::string const profile = "normal";

		std::regex fareg("(\\.fa|\\.fasta)$");

		std::string const dictfn = std::regex_replace(ref,fareg,std::string()) + ".dict";

		if ( ! libmaus2::util::GetFileSize::fileExists(dictfn) )
		{
			std::cerr << "[E] sequence dictionary " << dictfn << " does not exist, please create it using CreateSequenceDictionary (GATK)" << std::endl;
			return EXIT_FAILURE;
		}

		char const * ref_cache = getenv("REF_CACHE");

		if ( ! ref_cache )
		{
			std::cerr << "[E] REF_CACHE variable is not set" << std::endl;
			return EXIT_FAILURE;
		}

		std::filesystem::path ref_cache_path(ref_cache);
		std::set<std::filesystem::path> Spathseen;

		while ( std::filesystem::exists(ref_cache_path) && std::filesystem::is_symlink(ref_cache_path) )
		{
			if ( Spathseen.find(ref_cache_path) != Spathseen.end() )
			{
				std::cerr << "[E] circular loop of symlinks detected for REF_CACHE path" << std::endl;
				return EXIT_FAILURE;
			}

			Spathseen.insert(ref_cache_path);

			auto n_ref_cache_path = std::filesystem::read_symlink(ref_cache_path);

			ref_cache_path = n_ref_cache_path;
		}

		if ( !std::filesystem::exists(ref_cache_path) )
		{
			std::cerr << "[E] REF_CACHE directory " << ref_cache_path << " does not exist" << std::endl;
			return EXIT_FAILURE;
		}

		// std::cerr << "[V] using REF_CACHE path " << ref_cache_path << std::endl;

		libmaus2::parallel::threadpool::bam::BamHeaderSeqData seqdata(dictfn);

		if ( seqdata.sequencesMissing(ref_cache_path) )
		{
			std::cerr << "[V] scanning FastA file " << ref << " as REF_CACHE is incomplete" << std::endl;

			libmaus2::fastx::FastAReader FA(ref);
			libmaus2::fastx::FastAReader::pattern_type pat;

			while ( FA.getNextPatternUnlocked(pat) )
			{
				std::size_t o = 0;
				std::string & s = pat.spattern;
				for ( std::size_t i = 0; i < s.size(); ++i )
					if ( (i >= 33) && (i <= 126) )
						s[o++] = ::toupper(s[i]);
				s.resize(o);

				std::string digest;
				bool const ok = libmaus2::util::MD5::md5(s,digest);

				if ( ! ok )
				{
					std::cerr << "[E] failed to compute md5 checksum for " << pat.sid << " in " << ref << std::endl;
					return EXIT_FAILURE;
				}

				std::filesystem::path dictpath = ref_cache_path;
				dictpath /= digest;

				std::cerr << "[V] writing " << dictpath << " for " << pat.sid << " in " << ref << std::endl;
				libmaus2::aio::OutputStreamInstance OSI(dictpath.string());
				OSI << s;
				OSI.flush();
			}
		}

		if ( seqdata.sequencesMissing(ref_cache_path) )
		{
			std::cerr << "[E] unable to create required REF_CACHE files (mismatch between dictionary and FastA?)" << std::endl;
			return EXIT_FAILURE;
		}

		std::size_t const hwthreads = libmaus2::parallel::NumCpus::getNumLogicalProcessors();

		std::size_t argthreads = arg.getParsedArgOrDefault<std::size_t>("t", hwthreads);
		if ( ! argthreads )
			argthreads = hwthreads;

		std::size_t const inputblocks = 64;
		std::size_t const inputblocksize = 256*1024;
		std::size_t const cramblockaccum = 64;
		std::size_t const numdecompressedblocks = argthreads*cramblockaccum;
		std::size_t const seqs_per_slice = 0;
		std::size_t const bases_per_slice = 0;
		std::string const cramversion; // = "4.0";

		libmaus2::parallel::threadpool::ThreadPool TP(argthreads);

		std::shared_ptr<std::istream> ptr(&std::cin, []([[maybe_unused]]auto p){});

		libmaus2::parallel::threadpool::cram::ThreadPoolCramEnqueueControl TPBDC(
			TP,
			std::vector< std::shared_ptr<std::istream> >(1,ptr),
			seqdata,inputblocks,inputblocksize,numdecompressedblocks,cramblockaccum,profile,
			seqs_per_slice,
			bases_per_slice,
			cramversion
		);

		TPBDC.start();

		TP.join();

		std::cerr << "[V] finished and joined" << std::endl;
	}
	catch(std::exception const & ex)
	{
		std::cerr << ex.what() << std::endl;
		return EXIT_FAILURE;
	}
}
