# feature _markdown_helper.py
import tkinter as tk
from tkinter import filedialog, messagebox
import os

class FeatureListApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Feature List Checker")
        self.root.geometry("650x500")
        
        self.filepath_var = tk.StringVar()
        self.file_lines = []
        self.sections = []  # [(section_title, [ (BooleanVar, line_idx) ])]

        # Top frame: browse + save
        frame_top = tk.Frame(root)
        frame_top.pack(fill="x", padx=10, pady=5)
        entry_file = tk.Entry(frame_top, textvariable=self.filepath_var)
        entry_file.pack(side="left", fill="x", expand=True)
        tk.Button(frame_top, text="Browse", command=self.load_file).pack(side="left", padx=5)
        tk.Button(frame_top, text="Save", command=self.save_file).pack(side="left", padx=5)

        # Canvas for scrollable checklist
        self.canvas = tk.Canvas(root)
        self.scrollbar = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = tk.Frame(self.canvas)

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )

        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=self.scrollbar.set)

        self.canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")

    def load_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Markdown files", "*.md"), ("All files", "*.*")],
            title="Select Feature List File"
        )
        if not path:
            return
        self.filepath_var.set(path)
        self.refresh_checklist(path)

    def refresh_checklist(self, path):
        # Clear previous widgets
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        self.sections = []
        self.file_lines = []
        current_section = None

        with open(path, "r", encoding="utf-8") as f:
            lines = f.readlines()
        
        for idx, line in enumerate(lines):
            self.file_lines.append(line)
            stripped = line.strip()
            if stripped.startswith("##"):  # Section heading
                section_title = stripped
                frame = tk.Frame(self.scrollable_frame, relief="raised", bd=1)
                frame.pack(fill="x", pady=2)
                
                # Toggle button
                btn = tk.Button(frame, text=section_title, anchor="w", relief="flat")
                btn.pack(fill="x")
                
                content_frame = tk.Frame(frame)
                content_frame.pack(fill="x")
                
                # Store section
                current_section = {"title": section_title, "frame": content_frame, "items": [], "visible": True}
                self.sections.append(current_section)
                
                # Toggle function
                def toggle(f=current_section):
                    if f["visible"]:
                        f["frame"].pack_forget()
                        f["visible"] = False
                    else:
                        f["frame"].pack(fill="x")
                        f["visible"] = True
                btn.config(command=toggle)
                
            elif stripped.startswith("- [ ]") or stripped.startswith("- [x]"):
                if current_section is None:
                    # If no heading yet, create a default section
                    current_section = {"title": "No Section", "frame": tk.Frame(self.scrollable_frame), "items": [], "visible": True}
                    self.sections.append(current_section)
                    current_section["frame"].pack(fill="x")
                
                var = tk.BooleanVar()
                var.set(stripped.startswith("- [x]"))
                cb = tk.Checkbutton(current_section["frame"], text=stripped[6:].strip(), variable=var, anchor="w", justify="left")
                cb.pack(fill="x", padx=5)
                current_section["items"].append((var, idx))

    def save_file(self):
        if not self.filepath_var.get():
            messagebox.showerror("Error", "No file loaded.")
            return

        for section in self.sections:
            for var, idx in section["items"]:
                checked = "[x]" if var.get() else "[ ]"
                rest = self.file_lines[idx][6:].rstrip("\n")
                self.file_lines[idx] = f"- {checked} {rest}\n"
        
        with open(self.filepath_var.get(), "w", encoding="utf-8") as f:
            f.writelines(self.file_lines)
        messagebox.showinfo("Saved", f"Feature list saved to {self.filepath_var.get()}")


if __name__ == "__main__":
    root = tk.Tk()
    app = FeatureListApp(root)
    root.mainloop()