import pandas as pd
import sys
import os
import json
import traceback

if len(sys.argv) < 2:
    sys.stderr.write("Error: Missing file path argument.\n")
    sys.exit(1)

file_path = sys.argv[1]

try:
    # --- 1. FILE READING: Attempt robust text/CSV read first ---
    df = None
    read_success = False

    try:
        # PATH A: Treat as a Delimited Text file (CSV, TXT)
        # We rely on pandas' auto-detection (sep=None) and Python engine.
        df = pd.read_csv(
            file_path,
            encoding='utf-8-sig',
            sep=None,  # Auto-detects delimiter
            engine='python',
            encoding_errors='ignore',
            header=None  # Read first row as data
        )
        read_success = True
    except pd.errors.ParserError:
        # This is a common exception if the file is truly binary (non-CSV).
        # sys.stderr.write(f"DEBUG: CSV read failed with ParserError (File is likely Excel binary).\n")
        read_success = False
    except Exception as e_csv:
        # Catch other CSV-related exceptions (e.g., encoding issues that don't fit ParserError)
        # Log the error and proceed to the Excel reader.
        # sys.stderr.write(f"DEBUG: CSV read failed with error: {e_csv}. Attempting Excel read.\n")
        read_success = False


    if not read_success:
        # PATH B: Attempt to read as a true Binary Excel file (.xlsx or .xls)
        # sys.stderr.write(f"DEBUG: Attempting Excel read...\n")

        try:
            # 1. Try modern format (xlsx) using openpyxl (this caused the error).
            df = pd.read_excel(file_path, sheet_name=0, engine='openpyxl', header=None)
        except (ImportError, Exception) as e_openpyxl:
            # openpyxl fails on BadZipFile for older .xls. Now we explicitly try xlrd.
            # sys.stderr.write(f"DEBUG: openpyxl failed: {e_openpyxl}. Trying xlrd for .xls.\n")

            try:
                # 2. Fallback for older .xls (requires xlrd package)
                df = pd.read_excel(file_path, sheet_name=0, engine='xlrd', header=None)
            except Exception as e_xlrd:
                # If both Excel attempts fail, raise a comprehensive error.
                raise Exception(f"Failed all read attempts (CSV, openpyxl, xlrd). Last Excel error: {e_xlrd}")


    # --- 2. CONVERSION AND OUTPUT ---

    if df is None or df.empty:
        sys.stderr.write(f"Error: File {file_path} is empty or could not be read.\n")
        sys.exit(1)

    # Drop the first row (the original headers) and reset the index to 0, 1, 2...
    df_data_only = df.iloc[1:].reset_index(drop=True)
    df_data_only = df_data_only.astype(object)
    df_data_only = df_data_only.where(pd.notna(df_data_only), None)


    # Convert to the desired JSON structure: { "0": [v1, v2, ...], "1": [v1, v2, ...] }

    data_list = df_data_only.values.tolist()
    result_dict = {str(idx): row_data for idx, row_data in enumerate(data_list)}

    # ensure_ascii=False is necessary for correct handling of Persian characters.
    json_output = json.dumps(result_dict, indent=4, ensure_ascii=False)

    print(json_output)

except FileNotFoundError:
    sys.stderr.write(f"Error: File not found at {file_path}\n")
    sys.exit(1)
except Exception as e:
    # Print the full stack trace to stderr for debugging
    sys.stderr.write("--- Full Traceback Start ---\n")
    traceback.print_exc(file=sys.stderr)
    sys.stderr.write("--- Full Traceback End ---\n")
    # Catch all remaining exceptions, including the failed attempts to read the file
    sys.stderr.write(f"Conversion failed for {file_path}. Error: {e}\n")
    sys.exit(1)
