import argparse
import configparser
import shutil
import sys
import traceback

from importlib.metadata import version
from pathlib import Path

from lamfail.lamfailIO import LamfailIO
from lamfail.expiry_wrapper import check_expiry

__version__ = version("3pc-lamfail")

def main():
    """Entry point of the command line application - lamfail."""
    #check_expiry()

    parser = argparse.ArgumentParser(description='lamfail : Stress \
    / Strain Analysis of Anisotropic laminate Plates \
    Under Hygrothermal and Mechanical Loads.')
    parser.add_argument("config", type=str, nargs='?', default=None, help="specify configuration file")
    parser.add_argument("-v", "--version", help="show version number", action='version', version='3pc-%(prog)s ' + __version__)
    parser.add_argument("-s", "--sample", help="copy example files in the current directory", action="store_true")
    args = parser.parse_args()

    if args.sample:
        print('Copying sample file in current folder...')
        examples = Path(__file__).parent / 'examples'
        destination = Path(".") / 'examples'
        shutil.copytree(examples, destination, dirs_exist_ok=True)
        sys.exit()

    if args.config is None:
        sys.exit("No config file to run analysis. Try lamfail -h")
    
    config = configparser.ConfigParser()
    config.read(args.config)

    materialFile = config["files"]["materials"]
    plyFile = config["files"]["plies"]
    laminateFile = config["files"]["laminates"]
    panelFile = config["files"]["panels"]
    loadsFile = config["files"]["loads"]
    outputFile = config["files"]["output"]
    analysisType = config["analysis"]["analysis_type"]
    failureTheory = config["analysis"]["failure_theory"]

    lmfIO = LamfailIO(materialFile=materialFile, plyFile=plyFile,
    laminateFile=laminateFile, panelFile=panelFile, loadsFile=loadsFile, 
    outputFile=outputFile, analysisType=analysisType, failureTheory=failureTheory)
    try:
        lmfIO._writeResults()
    except Exception as lmfIOError:
        with open(outputFile, 'w') as fh:
            traceback.print_exc(limit=None, file=fh, chain=True)

