import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from django.core.management.base import BaseCommand, CommandError
from collections import defaultdict
import re

class Command(BaseCommand):
    help = 'Fetches all links from <nav> elements of a given URL and displays them in a tree-like structure.'

    def add_arguments(self, parser):
        parser.add_argument('url', type=str, help='The full URL of the HTML page to fetch (e.g., http://mysite.com)')

    def handle(self, *args, **options):
        url = options['url']

        # Validate URL format
        if not re.match(r'^https?://', url):
            raise CommandError('Please provide a valid URL starting with http:// or https://')

        try:
            # Fetch the HTML page
            response = requests.get(url, timeout=10)
            response.raise_for_status()  # Raise an error for bad status codes
        except requests.RequestException as e:
            raise CommandError(f'Error fetching URL {url}: {e}')

        # Parse HTML with BeautifulSoup
        soup = BeautifulSoup(response.text, 'html.parser')

        # Find all <nav> elements
        nav_elements = soup.find_all('nav')
        if not nav_elements:
            self.stdout.write('No <nav> elements found on the page.')
            return

        # Structure to hold the tree
        tree = defaultdict(list)

        # Process each <nav> element
        for idx, nav in enumerate(nav_elements, 1):
            nav_key = f'Navigation Menu {idx}'
            links = nav.find_all('a', href=True)
            for link in links:
                href = link['href']
                # Convert relative URLs to absolute
                absolute_url = urljoin(url, href)
                # Get link text, stripping whitespace, or use URL if text is empty
                link_text = link.get_text(strip=True) or absolute_url
                tree[nav_key].append((link_text, absolute_url))

        # Display the tree
        self.display_tree(tree)

    def display_tree(self, tree):
        """
        Display the navigation links in a tree-like structure.
        """
        for nav_key, links in tree.items():
            self.stdout.write(nav_key)
            for i, (link_text, link_url) in enumerate(links):
                prefix = '└── ' if i == len(links) - 1 else '├── '
                self.stdout.write(f'{prefix}{link_text} ({link_url})')
            self.stdout.write('')  # Newline after each nav section