#!/usr/bin/env python

import argparse
from pathlib import Path
import pandas as pd

from yamld.read import read_onelist_dataframe_from_file
from yamld.write import write_dataframe_from_path


def yaml2yaml(inpath, outpath=None, skiprows=None, nrows=None, is_mini=False, encoding='utf-8'):
    inpath = Path(inpath)
    suffix = inpath.suffix
    if outpath:
        outpath = Path(outpath)
    else:
        outpath = inpath.with_suffix('.mini.yaml')

    df = read_onelist_dataframe_from_file(inpath)
    write_dataframe_from_path(outpath, df.iloc[skiprows:nrows], is_mini=is_mini, encoding=encoding)


def parse_arguments():
    parser = argparse.ArgumentParser(description='Read CSV file using Pandas read_csv() function.')

    parser.add_argument('file_path', type=str, help='Path to the CSV file')


    # Optional arguments
    parser.add_argument('-o', '--output', type=str, default=None,
                        help='Character indicating the start of a comment line in the CSV file')

    parser.add_argument('-m', '--mini', action='store_true',
                        help='Specify if the CSV file has a header row')

    parser.add_argument("-n", "--nrows", type=int, default=None, help="Max number of lines to read from the file")

    parser.add_argument("--skiprows", type=int, default=None, help="Max number of lines to read from the file")
    parser.add_argument('-e', '--encoding', type=str, default='utf-8',
                        help='Character indicating the start of a comment line in the CSV file')

    return parser.parse_args()

def main():
    # Check if the script is being run as the main program
    # Parse command line arguments
    args = parse_arguments()

    # Read CSV file using Pandas read_csv() function
    try:
        yaml2yaml(args.file_path, args.output, skiprows=args.skiprows, nrows=args.nrows, is_mini=args.mini, encoding=args.encoding)
    except FileNotFoundError:
        print(f"Error: File not found at {args.file_path}")
    except pd.errors.EmptyDataError:
        print(f"Error: The CSV file at {args.file_path} is empty")


# Run the main function
if __name__ == "__main__":
    main()
