import os

def get_input(prompt, required=False):
    """Helper function to handle user input and require a value if needed."""
    while True:
        value = input(prompt).strip()
        if not value and required:
            print("This field is required. Please enter a value.")
            continue
        return value

def add_wishlist_item():
    filename = "/var/www/joelthegreat.com/wishlist.html"
    
    # Check if index.html exists in the current folder
    if not os.path.exists(filename):
        print(f"Error: {filename} not found in the current directory.")
        return

    print("--- Add New Wishlist Item ---")
    
    # Gather inputs interactively
    name = get_input("Item Name: ", required=True)
    url = get_input("URL (Optional): ")
    price = get_input("Estimated Cost ($): ", required=True)
    notes = get_input("Notes (Optional): ")

    # Clean up price formatting (add dollar sign if missing)
    if not price.startswith('$'):
        price = f"${price}"

    # Build the HTML string based on whether a URL is provided
    if url:
        item_td = f'<td>\n                        <a href="{url}" target="_blank" class="item-link">{name}</a>\n                    </td>'
    else:
        item_td = f'<td>{name}</td>'

    # Construct the full table row snippet
    new_row = f"""                <tr>
                    {item_td}
                    <td>{price}</td>
                    <td>{notes if notes else '-'}</td>
                </tr>
"""

    # Target line to look for
    target_comment = '<!-- Add your next item right below this line using the format above -->'

    # Read the file and look for the target line
    with open(filename, "r", encoding="utf-8") as file:
        lines = file.readlines()

    success = False
    new_lines = []
    
    for line in lines:
        new_lines.append(line)
        # If we match the comment line, insert our new row right after it
        if target_comment in line:
            new_lines.append(new_row)
            success = True

    if not success:
        print(f"\nError: Could not find the target comment line in {filename}.")
        print("Make sure the exact comment line exists in your HTML file.")
        return

    # Write the modified content back to the file
    with open(filename, "w", encoding="utf-8") as file:
        file.writelines(new_lines)

    print(f"\nSuccessfully added '{name}' to {filename}!")

if __name__ == "__main__":
    add_wishlist_item()
