from html.parser import HTMLParser

class TagMatcher(HTMLParser):
    def __init__(self):
        super().__init__()
        self.stack = []
        self.div_map = {} # line -> info
        self.errors = []
        
    def handle_starttag(self, tag, attrs):
        if tag == 'div':
            attr_dict = dict(attrs)
            div_id = attr_dict.get('id', '')
            div_class = attr_dict.get('class', '')
            line_no = self.getpos()[0]
            
            info = {
                'tag': 'div',
                'id': div_id,
                'class': div_class,
                'start_line': line_no,
                'parent': self.stack[-1]['id'] if self.stack else None
            }
            self.stack.append(info)

    def handle_endtag(self, tag):
        if tag == 'div':
            if self.stack:
                info = self.stack.pop()
                info['end_line'] = self.getpos()[0]
                
                # Store important divs
                if info['id'] in ['fileTabsContent', 'processed', 'repository', 'repoTabsContent', 'pills-backup', 'pills-mac', 'pills-guid', 'pills-gpu']:
                    self.div_map[info['id']] = info
            else:
                self.errors.append(f"Unexpected closing div at line {self.getpos()[0]}")

    def validate(self, html_content):
        self.feed(html_content)
        
        print("=== DIV STRUCTURE MAP ===\n")
        order = ['fileTabsContent', 'processed', 'repository', 'repoTabsContent', 'pills-backup', 'pills-mac', 'pills-guid', 'pills-gpu']
        
        for div_id in order:
            if div_id in self.div_map:
                info = self.div_map[div_id]
                print(f"ID: {div_id}")
                print(f"  Start: {info['start_line']}")
                print(f"  End:   {info['end_line']}")
                print(f"  Parent: {info['parent']}")
                print()
            else:
                print(f"ID: {div_id} - NOT FOUND or NOT CLOSED properly\n")
        
        if self.stack:
            print("\n=== UNCLOSED DIVS ===")
            for info in self.stack:
                print(f"Unclosed div starting at line {info['start_line']} (ID: {info['id']}, Class: {info['class']})")

# Read the file
file_path = r"d:\Code\iDRAC_Info\idrac_info\backend\templates\index.html"
with open(file_path, "r", encoding="utf-8") as f:
    content = f.read()

matcher = TagMatcher()
matcher.validate(content)
