import subprocess
import igl
import argparse
import os
import numpy as np
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument('input',  type=str)
parser.add_argument('output', type=str)
parser.add_argument('vertex', type=str)

args = parser.parse_args()

input_obj_fn = args.input 
output_obj_fn = args.output
input_off_fn = str(Path(input_obj_fn).with_suffix('.off'))
input_obj_uv_fn = str(Path(input_obj_fn).parent / 'remesh_uv.obj')

v, _, _, f, _, _ = igl.read_obj(input_obj_fn)
igl.write_triangle_mesh(input_off_fn, v, f)

print("\nMeshFix:")
subprocess.run(["MeshFix", input_off_fn, output_obj_fn])
os.remove(input_off_fn)

print("\nInstant_meshes:")
subprocess.run(['instant_meshes', '-o', output_obj_fn, '-t', '32', '-S', '10', '-d', '-p', '6', '-v', args.vertex, output_obj_fn])

v, _, _, f, _, _ = igl.read_obj(input_obj_fn)
igl.write_triangle_mesh(input_off_fn, v, f)

print("\nMeshFix:")
subprocess.run(["MeshFix", input_off_fn, output_obj_fn])
os.remove(input_off_fn)

print("\nBFF:")
subprocess.run(['bff-command-line', output_obj_fn, input_obj_uv_fn, '--nCones=8', '--normalizeUVs'])

print("\nAlign BFF:")
v1, vt, _, f1, ft, _ = igl.read_obj(input_obj_uv_fn)
assert(np.shape(f1) == np.shape(ft))
os.remove(input_obj_uv_fn)
v2, _, _, f2, _, _ = igl.read_obj(output_obj_fn)

vp = v1 + np.mean(v2 - v1, axis=0)

vt_max, vt_min = vt.max(), vt.min()
vt_span = vt_max - vt_min
vt = (vt - vt_min) / vt_span

with open(output_obj_fn, "w") as file:
	f1 +=1
	ft += 1

	for v in vp:
		file.write(f'v {v[0]} {v[1]} {v[2]}\n')

	for tc in vt:
		file.write(f'vt {tc[0]} {tc[1]}\n')

	for f, ftc in zip(f1, ft):
		file.write(f'f {f[0]}/{ftc[0]} {f[1]}/{ftc[1]} {f[2]}/{ftc[2]}\n')