import sys
import os
import tempfile
import json
import pathlib
from biodata.baseio import get_text_file_extension

# RMS Core
from rmsp import rmscore, rmsutils, rmsbuilder
from rmsp.rmstemplate import RMSTemplateLibrary
from rmsp.rmscore import ResourceManagementSystem

# Interactor
import threading
from rmsp.rmsinteractor import RMSPoolInteractionCore, RMSInteractionCore, RMSTemplateLibraryInteractionCore
from rmsp.interactorhelper import RemoteInteractorServer

from commonhelper import convert_to_bool

import simplevc
simplevc.register(sys.modules[__name__], "0.1.1")

@vt()
@vc
def _setup_wizard_20240430(dbpath : str, dbname : str):
	dbpath = dbpath + "/"
	p = pathlib.Path(dbpath + "RMSResources/")
	p.mkdir(parents=True, exist_ok=True)
	p = pathlib.Path(dbpath + "RMSLibrary/")
	p.mkdir(parents=True, exist_ok=True)
	rmsutils.create_new_db(dbpath + dbname)
	
@vt()
@vc
def _register_files_20240430(dbpath: str, dbname: str, files : list[str]):
	dbpath = dbpath + "/"
	dbfile = dbpath + dbname
	rms = ResourceManagementSystem(dbfile)
	for f in files:
		rms.register_file(os.path.abspath(f))
	

@vt()
@vc
def _execute_template_commands_20240430(
		dbpath: str, dbname: str, parameter_files: list[str],
		builder_mode:convert_to_bool=True, nthread:int=8
		):
	if dbpath == "":
		rms= rmsutils.create_virtual_rms()
	else:
		dbpath = dbpath + "/"
		rms = ResourceManagementSystem(dbpath + dbname, dbpath + "RMSResources/")
	
	libpath = dbpath + "RMSLibrary/"
	
	# Check library
	book_edition_set = set()
	for parameter_file in parameter_files:
		extension = get_text_file_extension(parameter_file)
		if extension == "json":
			with open(parameter_file, "rt") as f:
				parameters_entries = json.load(f)
		else:
			raise Exception("Unsupported parameter file format")
		for parameters_entry in parameters_entries["commands"]:
			book_edition_set.add((parameters_entry["bookname"], parameters_entry["editionname"]))
	# Attempt to resolve all required libraries
	unresolved = []
	for bookname, editionname in sorted(book_edition_set):
		if not os.path.exists(f'{libpath}{bookname}/{editionname}/manifest.json'):
			print("Missing book edition: " + f'{bookname} {editionname}')
			_download_templates_20250701(dbpath, bookname, editionname)
			if not os.path.exists(f'{libpath}{bookname}/{editionname}/manifest.json'):
				print("Fail to download " + f'{bookname} {editionname}')
				unresolved.append((bookname, editionname))
			else: 
				print("Downloaded " + f'{bookname} {editionname}')
	if len(unresolved) > 0:
		print("The following book edition could not be downloaded:")
		for bookname, editionname in unresolved:
			print(f'{bookname} {editionname}')
		raise Exception("Fail to load library")
	
	
	if builder_mode:
		rmspool = rmsbuilder.RMSProcessWrapPool(rms, nthread)
		rmsb = rmsbuilder.RMSUnrunTasksBuilder(rmspool)
		rmstlib = RMSTemplateLibrary(rmsb, libpath)
	else:
		rmstlib = RMSTemplateLibrary(rms, libpath)
	
	for parameter_file in parameter_files:
		extension = get_text_file_extension(parameter_file)
		if extension == "json":
			with open(parameter_file, "rt") as f:
				parameters_entries = json.load(f)
		else:
			raise Exception("Unsupported parameter file format")
		for parameters_entry in parameters_entries["commands"]:
			rmstlib.run(parameters_entry["bookname"], parameters_entry["editionname"], parameters_entry["bookmark"].split(","), [], parameters_entry["parameters"])
	
	if builder_mode:
		rmsb.execute_builder()
		rmspool.close()
	
@vt()
@vc
def _start_server_20240430(
		dbpath: str, dbname: str, nthread:int=8,
		host="localhost",
		rms_port=8001,
		rmspool_port=8002,
		rmstlib_port=8003,
		 
	):
	dbpath = dbpath + "/"
	libpath = dbpath + "RMSLibrary/"
	rms = ResourceManagementSystem(dbpath + dbname, dbpath + "RMSResources/")
	rmspool = rmsbuilder.RMSProcessWrapPool(rms, nthread)
	rmsb = rmsbuilder.RMSUnrunTasksBuilder(rmspool)
	rmstlib = RMSTemplateLibrary(rmsb, libpath)
	
	
	rms_server = RemoteInteractorServer(RMSInteractionCore(rms), host, rms_port)
	rmspool_server = RemoteInteractorServer(RMSPoolInteractionCore(rmspool), host, rmspool_port)
	rmstemplatelib_server = RemoteInteractorServer(RMSTemplateLibraryInteractionCore(rmstlib), host, rmstlib_port)
	threading.Thread(target=rms_server.serve).start()
	threading.Thread(target=rmspool_server.serve).start()
	threading.Thread(target=rmstemplatelib_server.serve).start()
	
	
@vt()
@vc
def _download_templates_20250701(dbpath: str, bookname: str, editionname: str):
	download_link = "https://github.com/aldenleung/rmsp-library.git"
	dbpath = os.path.abspath(dbpath) + "/"
	with tempfile.TemporaryDirectory() as temp_dir:
		os.system(f"cd {temp_dir}; git clone --no-checkout {download_link}; cd rmsp-library; git sparse-checkout set --no-cone '/RMSLibrary/{bookname}/{editionname}/**/*'; git checkout; mkdir -p {dbpath}RMSLibrary/{bookname}/{editionname}; mv RMSLibrary/{bookname}/{editionname} {dbpath}RMSLibrary/{bookname}/")
	
if __name__ == "__main__":
	main()
