import meshio
import argparse
import subprocess as sp
import os

def generateMesh(coreMeshRes, outerMeshRes, k, order):
    # gmsh sphere.geo -3 -setnumber Parameters/Order 1 -setnumber Parameters/CoreRes 0.2 -setnumber Parameters/OuterRes 0.4 -setnumber Parameters/K 2.0 -o sphere_order2.msh
    gmsh_cmd = [
        'gmsh',
        'sphere.geo',  # Path to your GMSH geometry file
        '-3',  # Generate 3D mesh
        '-setnumber', 'Parameters/Order', str(order),
        '-setnumber', 'Parameters/CoreRes', str(coreMeshRes),
        '-setnumber', 'Parameters/OuterRes', str(outerMeshRes),
        '-setnumber', 'Parameters/K', str(k),
        '-o', 'sphere.vtk',  # Output mesh file
        '-format', 'vtk'

    ]
    # Use popen to run
    process = sp.Popen(gmsh_cmd)
    stdout, stderr = process.communicate()
    if process.returncode != 0:
        print(f"Error generating mesh: {stderr.decode()}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Generate a spherical mesh')
    parser.add_argument('--coreMeshRes', type=float, default=0.1, help='Core Mesh Resolution target')
    parser.add_argument('--outerMeshRes', type=float, default=0.3, help='Outer Mesh Resolution target')
    parser.add_argument('--k', type=float, default=2, help='Mesh size scaling factor')

    # Add argument for element order
    parser.add_argument('--order', type=int, default=2, help='Mesh element order (e.g., 1 for linear, 2 for quadratic)')
    parser.add_argument('--output', type=str, default='sphere.vtk', help='Output file name')
    args = parser.parse_args()

    # Generate the mesh
    generateMesh(args.coreMeshRes, args.outerMeshRes, args.k, args.order)

