from html.parser import HTMLParser
import sys

class DetailedDivValidator(HTMLParser):
    def __init__(self):
        super().__init__()
        self.stack = []
        self.errors = []
        self.important_divs = ['fileTabsContent', 'processed', 'repository', 'repoTabsContent', 'pills-backup']
        
    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]
            self.stack.append({
                'tag': 'div',
                'id': div_id,
                'class': div_class,
                'line': line_no
            })
            
            if div_id in self.important_divs:
                print(f"Line {line_no:4d}: OPEN  <div id=\"{div_id}\" class=\"{div_class}\"> (depth: {len(self.stack)})")

    def handle_endtag(self, tag):
        if tag == 'div':
            if not self.stack:
                line_no = self.getpos()[0]
                self.errors.append(f"Line {line_no}: Unexpected </div> - no matching opening tag")
                print(f"Line {line_no:4d}: ERROR - Unexpected </div>")
                return
            
            opened = self.stack.pop()
            line_no = self.getpos()[0]
            
            if opened['id'] in self.important_divs:
                print(f"Line {line_no:4d}: CLOSE </div> (was id=\"{opened['id']}\", opened at line {opened['line']}, depth: {len(self.stack)+1})")

    def validate(self, html_content):
        self.feed(html_content)
        
        if self.stack:
            print("\n=== UNCLOSED DIVS ===")
            for item in self.stack:
                print(f"Line {item['line']}: Unclosed <div id=\"{item['id']}\" class=\"{item['class']}\">")
                self.errors.append(f"Line {item['line']}: Unclosed <div id=\"{item['id']}\">")
        
        return self.errors

# 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()

print("=== IMPORTANT DIV STRUCTURE ===\n")
validator = DetailedDivValidator()
errors = validator.validate(content)

if errors:
    print("\n=== ERRORS FOUND ===")
    for error in errors:
        print(error)
    sys.exit(1)
else:
    print("\n=== NO ERRORS FOUND ===")
    sys.exit(0)
