import tkinter as tk
from tkinter import filedialog

# Tkinter file picker
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(
    title="Select your export list file",
    filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)

if not file_path:
    print("No file selected.")
    exit()

output_lines = []
current_series = None
counter = 0

with open(file_path, "r", encoding="utf-8") as f:
    for line in f:
        parts = line.strip().split(";")
        if len(parts) < 4:
            output_lines.append(line.strip())
            continue

        product, series, lesson, category, *rest = parts

        # Detect when we move to a new series
        if series != current_series:
            current_series = series
            counter = 0

        # If lesson starts with "?.", replace with proper numbering
        if lesson.startswith("?."):
            counter += 1
            lesson = f"{counter}.{lesson[2:].strip()}"
        else:
            # If already numbered, keep as-is
            counter += 1

        # Rebuild line
        rebuilt = ";".join([product, series, lesson, category] + rest)
        output_lines.append(rebuilt)

# Print corrected output
for line in output_lines:
    print(line)
