import os
import openpyxl

print("""Αυτό το script μετατρέπει αρχεία Excel από την μορφή των Google Forms
σε μορφή συμβατή για εισαγωγή στο SPSS""")

# Step 1: List all .xlsx files in the current directory
xlsx_files = [f for f in os.listdir('.') if f.endswith('.xlsx')]

if not xlsx_files:
    #print("No .xlsx files found in the current directory.")
    print("""Δεν βρέθηκαν αρχεία Excel σε αυτό τον φάκελο. Δοκίμασε
να μεταφέρεις το αρχείο 'metatropeas.py' στον ίδιο φάκελο
με το αρχείο Excel από τα Google Forms""")
else:
    # Display available files to the user
    #print("Available .xlsx files:")
    print("Διαθέσιμα αρχεία .xlsx:")
    for idx, file_name in enumerate(xlsx_files):
        print(f"{idx + 1}: {file_name}")
    
    # Prompt the user to select a file
    file_choice = int(input("Γράψε τον αριθμό του αρχείου που θέλεις να μετατρέψεις: ")) - 1
    selected_file = xlsx_files[file_choice]

    # Load the selected workbook
    workbook = openpyxl.load_workbook(selected_file)
    print(f"\nΑρχείο '{selected_file}' ανοίχτηκε επιτυχώς.\n")

    # Step 2: Display available sheets in the workbook
    sheet_names = workbook.sheetnames
    print("Διαθέσιμα φύλλα εργασίας:")
    for idx, sheet_name in enumerate(sheet_names):
        print(f"{idx + 1}: {sheet_name}")
    
    # Prompt the user to select a sheet
    sheet_choice = int(input("Γράψε τον αριθμό του φύλλου εργασίας που θες να μετατρέψεις: ")) - 1
    selected_sheet = workbook[sheet_names[sheet_choice]]

    print(f"\nΔιάλεξες το φύλλο εργασίας: {sheet_names[sheet_choice]}")

    # Step 3: Display first row values to allow column selection
    first_row = list(selected_sheet.iter_rows(values_only=True, max_row=1))[0]
    print("\nΤίτλοι κάθε στήλης:")
    for idx, header in enumerate(first_row):
        print(f"{idx + 1}: {header}")

    # Prompt the user to select the first and last column by number
    first_column = int(input("Γράψε τον αριθμό της πρώτης στήλης: ")) - 1
    last_column = int(input("Γράψε τον αριθμό της τελευταίας στήλης: ")) - 1

    # Step 4: Prompt for ASCII-only column header names
    new_headers = []
    for col_idx in range(first_column, last_column + 1):
        original_header = first_row[col_idx]
        new_header = input(f"Παρακαλώ μετονόμασε την στήλη '{original_header}' ώστε να έχει μόνο λατινικούς χαρακτήρες: ")
        new_headers.append(new_header)

    # Prepare the output file for mappings
    print("================================")
    print("Data Labels:")
    mapping_filename = "data-labels.txt"
    with open(mapping_filename, "w", encoding="utf-8") as map_file:
        map_file.write(f"Τα Data Labels στο SPSS θα πρέπει να αντιστοιχούν ως εξής:\n\n")

        # Step 5: Create a new workbook for the remapped data
        new_workbook = openpyxl.Workbook()
        new_sheet = new_workbook.active
        new_sheet.title = "demographics"

        # Add 'id' column header
        new_sheet["A1"] = "id"

        # Add renamed headers to the new sheet
        for col_idx, new_header in enumerate(new_headers, start=2):
            new_sheet.cell(row=1, column=col_idx).value = new_header

        # Add 'id' values starting from 1 in the new sheet
        for row_idx in range(2, selected_sheet.max_row + 1):
            new_sheet.cell(row=row_idx, column=1).value = row_idx - 1  # Incremental id

        # Process each selected column independently
        for col in range(first_column + 1, last_column + 2):
            # Create a new value_map for each column to start numbering from 1
            value_map = {}
            current_number = 1

            # Map each cell in the column, starting from row 2
            for row in range(2, selected_sheet.max_row + 1):
                cell = selected_sheet.cell(row=row, column=col)

                # Create a unique mapping if value is not already mapped
                if cell.value not in value_map:
                    value_map[cell.value] = current_number
                    current_number += 1
                
                # Write the mapped number to the new sheet
                new_sheet.cell(row=row, column=col - first_column + 1).value = value_map[cell.value]

            # Log the mapping for this column in the text file and console
            header = new_headers[col - first_column - 1]
            map_file.write(f"variable '{header}':\n")
            print(f"\nData Labels μεταβλητής '{header}'")
            for original_value, mapped_value in value_map.items():
                map_file.write(f"  '{original_value}' -> {mapped_value}\n")
                print(f"  '{original_value}' -> {mapped_value}")
            map_file.write("\n")

    print("================================")
    # Save the new workbook with the 'id' column and remapped values
    new_filename = "spss-demographics.xlsx"
    new_workbook.save(new_filename)
    print(f"Το αρχείο Excel για εισαγωγή στο SPSS αποθηκεύτηκε ως '{new_filename}'")
    print(f"Τα Data Labels της κάθε μεταβλητής αποθηκεύτικαν στο αεχείο '{mapping_filename}'")
    print("\nmade by ynp. Info: https://www.yiannikos.gr/")
    print("2024 AD\n")
