import os
import sys
import xml.etree.ElementTree as ET

def xls_to_xml(input_file, output_file):
    """
    Convert an .xls or .xlsx file to an .xml file.
    """
    # Determine the file extension
    file_extension = os.path.splitext(input_file)[1].lower()

    # Create the root element for the XML
    root = ET.Element("Workbook")

    if file_extension == ".xls":
        try:
            import xlrd  # For .xls files
        except ModuleNotFoundError as exc:
            raise RuntimeError("Dependency missing for .xls conversion: install xlrd") from exc

        # Process .xls files using xlrd
        workbook = xlrd.open_workbook(input_file)
        sheet = workbook.sheet_by_index(0)  # Get the first sheet

        # Iterate through rows and columns to populate the XML
        for row_idx in range(sheet.nrows):
            row_values = sheet.row_values(row_idx)
            row_element = ET.SubElement(root, "Row")
            for col_idx, cell_value in enumerate(row_values):
                # Skip the last cell if it is empty
                if col_idx == len(row_values) - 1 and not cell_value:
                    continue
                cell_element = ET.SubElement(row_element, "Cell")
                cell_element.text = str(cell_value)

    elif file_extension == ".xlsx":
        try:
            from openpyxl import load_workbook  # For .xlsx files
        except ModuleNotFoundError as exc:
            raise RuntimeError("Dependency missing for .xlsx conversion: install openpyxl") from exc

        # Process .xlsx files using openpyxl
        workbook = load_workbook(input_file, data_only=True)
        sheet = workbook.active  # Get the first sheet

        # Iterate through rows and columns to populate the XML
        for row in sheet.iter_rows(values_only=True):
            row_element = ET.SubElement(root, "Row")
            for col_idx, cell_value in enumerate(row):
                # Skip the last cell if it is empty
                if col_idx == len(row) - 1 and (cell_value is None or cell_value == ""):
                    continue
                cell_element = ET.SubElement(row_element, "Cell")
                cell_element.text = str(cell_value) if cell_value is not None else ""

    else:
        raise ValueError("Unsupported file format. Please provide an .xls or .xlsx file.")

    # Write the XML to the output file
    tree = ET.ElementTree(root)
    with open(output_file, "wb") as xml_file:
        tree.write(xml_file, encoding="utf-8", xml_declaration=True)

    print(f"Successfully converted '{input_file}' to '{output_file}'.")

# Main logic
if __name__ == "__main__":
    # Check if the input and output file paths are provided
    if len(sys.argv) < 3:
        print("Usage: python3 xls_to_xml.py <input_file.xls|input_file.xlsx> <output_file.xml>")
        sys.exit(1)

    # Get the input and output file paths from the command-line arguments
    input_file = sys.argv[1]
    output_file = sys.argv[2]

    # Call the function to convert .xls or .xlsx to .xml
    try:
        xls_to_xml(input_file, output_file)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)