import os
import re

def remove_wishlist_item():
    # Dynamically find wishlist.html right next to this script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    filename = os.path.join(script_dir, "wishlist.html")
    
    if not os.path.exists(filename):
        print(f"Error: {filename} not found.")
        return

    with open(filename, "r", encoding="utf-8") as file:
        content = file.read()

    # Regex pattern to find all <tr> blocks inside the <tbody> section
    # It captures the full row block so we can delete it later
    row_pattern = re.compile(r'( +<tr>\s+<td>.*?</td>\s+</tr>\n)', re.DOTALL)
    rows = row_pattern.findall(content)

    if not rows:
        print("No items found in your wishlist table.")
        return

    print("--- Current Wishlist Items ---")
    items_list = []
    
    # Parse the item name out of each row to show the user
    for index, row in enumerate(rows, 1):
        # Strip out HTML tags to extract just the item name text
        name_match = re.search(r'<td>\s*(?:<a[^>]*>)?([^<\n]+)(?:</a>)?\s*</td>', row)
        item_name = name_match.group(1).strip() if name_match else f"Item #{index}"
        
        items_list.append((row, item_name))
        print(f"{index}. {item_name}")

    print("------------------------------")
    
    # Prompt user for which item to delete
    while True:
        choice = input("Enter the number of the item to remove (or 'q' to quit): ").strip()
        if choice.lower() == 'q':
            print("Cancelled.")
            return
        
        if choice.isdigit():
            choice_idx = int(choice) - 1
            if 0 <= choice_idx < len(items_list):
                break
        print("Invalid choice. Please enter a valid number from the list.")

    # Get the exact raw HTML string of the chosen row
    row_to_remove, target_name = items_list[choice_idx]

    # Replace the row with an empty string to delete it
    updated_content = content.replace(row_to_remove, "")

    with open(filename, "w", encoding="utf-8") as file:
        file.write(updated_content)

    print(f"\nSuccessfully removed '{target_name}' from wishlist.html!")

if __name__ == "__main__":
    remove_wishlist_item()
