#!/usr/bin/env python3
import re
import sys
from pathlib import Path

def remove_duplicate_bookmarks(input_file, output_file):
    try:
        content = Path(input_file).read_text(encoding='utf-8')
    except Exception as e:
        print(f"Error reading file: {e}")
        sys.exit(1)
        
    # Track unique URLs
    seen_urls = set()
    deduped_lines = []
    removed_count = 0
    
    # Regex to find href attribute values
    href_regex = re.compile(r'HREF="([^"]+)"', re.IGNORECASE)
    
    # Process line by line to keep HTML structure intact
    for line in content.splitlines():
        match = href_regex.search(line)
        if match:
            url = match.group(1)
            if url in seen_urls:
                removed_count += 1
                continue  # Skip this line (duplicate bookmark)
            else:
                seen_urls.add(url)
                deduped_lines.append(line)
        else:
            # Keep folder structures, headers, and metadata lines
            deduped_lines.append(line)
            
    try:
        Path(output_file).write_text('\n'.join(deduped_lines), encoding='utf-8')
        print(f"Successfully processed bookmarks!")
        print(f"Kept: {len(seen_urls)} unique bookmarks.")
        print(f"Removed: {removed_count} duplicates.")
        print(f"Cleaned file saved to: {output_file}")
    except Exception as e:
        print(f"Error writing file: {e}")
        sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python3 clean_bookmarks.py <path_to_exported_bookmarks.html>")
        sys.exit(1)
        
    infile = sys.argv[1]
    outfile = str(Path(infile).parent / f"cleaned_{Path(infile).name}")
    remove_duplicate_bookmarks(infile, outfile)
