
from html.parser import HTMLParser

class DivValidator(HTMLParser):
    def __init__(self):
        super().__init__()
        self.stack = []
        self.errors = []
        self.indent_level = 0
        
    def handle_starttag(self, tag, attrs):
        if tag == 'div':
            # Create a simplified representation of the div with id/class for identification
            attr_dict = dict(attrs)
            ident = ""
            if 'id' in attr_dict:
                ident += f"#{attr_dict['id']}"
            if 'class' in attr_dict:
                ident += f".{attr_dict['class'].replace(' ', '.')}"
            
            self.stack.append((self.getpos(), ident))
            # print(f"{'  ' * len(self.stack)}<div {ident}>")

    def handle_endtag(self, tag):
        if tag == 'div':
            if not self.stack:
                self.errors.append(f"Unexpected </div> at {self.getpos()}")
            else:
                pos, ident = self.stack.pop()
                # print(f"{'  ' * (len(self.stack) + 1)}</div> ({ident})")

    def validate(self, html_content):
        # Allow Jinja2 template tags to pass through, but we might have issues if they contain divs
        # For this specific case, we assume simple Jinja usage that doesn't split divs across blocks strangely
        self.feed(html_content)
        
        if self.stack:
            for pos, ident in self.stack:
                self.errors.append(f"Unclosed <div {ident}> starting at {pos}")
        
        return self.errors

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

validator = DivValidator()
errors = validator.validate(content)

if errors:
    print("Found HTML Structure Errors:")
    for error in errors:
        print(error)
else:
    print("No div nesting errors found.")
