#!/usr/bin/env python3
"""
Rebuild ___left.htm from the .hhc table of contents file
"""
import re
import sys

def parse_hhc(hhc_file):
    """Parse the HHC file and extract navigation structure"""
    with open(hhc_file, 'r', encoding='utf-8', errors='ignore') as f:
        content = f.read()
    
    # Extract all <object> blocks
    items = []
    level = 0
    in_ul = False
    
    lines = content.split('\n')
    for i, line in enumerate(lines):
        if '<ul>' in line.lower():
            level += 1
            in_ul = True
        elif '</ul>' in line.lower():
            level -= 1
        elif '<object type="text/sitemap">' in line.lower():
            # Get the next few lines to extract params
            obj_lines = []
            for j in range(i, min(i+10, len(lines))):
                obj_lines.append(lines[j])
                if '</object>' in lines[j].lower():
                    break
            
            # Parse params
            name = ''
            local = ''
            for ol in obj_lines:
                name_match = re.search(r'<param name="Name" value="([^"]+)"', ol, re.IGNORECASE)
                local_match = re.search(r'<param name="Local" value="([^"]+)"', ol, re.IGNORECASE)
                if name_match:
                    name = name_match.group(1)
                if local_match:
                    local = local_match.group(1)
            
            if name:
                items.append({
                    'level': level - 1,  # Adjust for 0-based
                    'name': name,
                    'url': local if local else ''
                })
    
    return items

def generate_left_htm(items):
    """Generate the ___left.htm HTML content"""
    
    html = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contents</title>
<link rel="StyleSheet" href="___dtree.css" type="text/css" />
<link rel="StyleSheet" href="prompttech-header.css" type="text/css" />
<script language="JavaScript" src="___dtree.js" type="text/javascript"></script>
</head>
<body class="dtreebody">
<div class="dtreecontainer">
<script type="text/javascript">
<!--
d = new dTree('d');
d.config.useCookies = false;
"""
    
    # Add root node
    html += "d.add(0,-1,'QuickBooks Point of Sale Help','qbpos_basic_procedures/basic_welcome.htm','QuickBooks Point of Sale Help','body');\n"
    
    # Add all items
    node_id = 1
    parent_stack = [0]  # Stack to track parent IDs at each level
    last_level = 0
    
    for item in items:
        level = item['level']
        name = item['name'].replace("'", "\\'")
        url = item['url'].replace("'", "\\'")
        
        # Adjust parent stack based on level changes
        if level > last_level:
            # Going deeper
            parent_stack.append(node_id - 1)
        elif level < last_level:
            # Going up - pop stack
            for _ in range(last_level - level):
                if len(parent_stack) > 1:
                    parent_stack.pop()
        
        parent_id = parent_stack[-1]
        
        # Add node
        if url:
            html += f"d.add({node_id},{parent_id},'{name}','{url}');\n"
        else:
            html += f"d.add({node_id},{parent_id},'{name}');\n"
        
        node_id += 1
        last_level = level
    
    html += """
document.write(d);
//-->
</script>
</div>
</body>
</html>"""
    
    return html

def main():
    hhc_file = '/home/pts/Documents/QBPOS_Help_Web/QB_Help_Web/POS_Help/POS_Help_v19R1_Feb_2020.hhc'
    output_file = '/home/pts/Documents/QBPOS_Help_Web/QB_Help_Web/POS_Help/___left.htm'
    
    print(f"Parsing {hhc_file}...")
    items = parse_hhc(hhc_file)
    print(f"Found {len(items)} navigation items")
    
    print(f"Generating {output_file}...")
    html = generate_left_htm(items)
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html)
    
    print(f"Successfully rebuilt ___left.htm with {len(items)} items")

if __name__ == '__main__':
    main()
