import csv
from pathlib import Path


def csv_to_index_txt(file_path) -> None:
    """
    Convert a Discovery density-extraction CSV file into a tab-delimited
    TXT file containing refractive index data.

    Processing:
    - Skip first row
    - Remove columns 4 and 6
    - Convert coordinates (columns 1-3) from m to mm
    - Convert density to refractive index using the Gladstone-Dale relation

    Accepts:
        str or pathlib.Path

    Output:
        <original_name>_Index.txt
    """

    file_path = Path(file_path)
    output_path = file_path.with_name(f"{file_path.stem}_Index.txt")

    wavelength_um = 1.2
    k_gd = 0.113 + 0.00092 * wavelength_um**-2

    with open(file_path, "r", encoding="utf-8", newline="") as infile, \
         open(output_path, "w", encoding="utf-8", newline="") as outfile:

        reader = csv.reader(infile)

        # Skip header row
        next(reader, None)

        for row in reader:

            # Need at least 6 columns before deleting
            if len(row) < 6:
                continue

            # Remove columns 6 and 4
            del row[5]
            del row[3]

            try:
                # Convert coordinates from m to mm
                for i in range(3):
                    row[i] = f"{float(row[i]) * 1000:.6f}"

                # Convert density to refractive index
                density = float(row[3])
                row[3] = f"{1.0 + density * k_gd:.9f}"

            except ValueError:
                continue

            outfile.write("\t".join(row) + "\n")

    print(f"Saved: {output_path}")


def main() -> None:

#Directory
    working_dir = OSL_DESIGN_DIR

#Reformatting and Recalculating
    for region in ["A", "B", "C"]:
        csv_file = working_dir + f"\Density_Region_{region}.csv"
        csv_to_index_txt(csv_file)
#Test print
    print(csv_file)

if __name__ == "__main__":
    main()