#!/usr/bin/env python3
"""
IEEE 802.1 Index Generator
Creates searchable HTML index from processed documents
"""

import sqlite3
import json
from datetime import datetime

def load_config():
    config = {}
    if os.path.exists('.env'):
        with open('.env', 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    config[key.strip()] = value.strip()
    return config

config = load_config()
BASE_PATH = config.get('BASE_PATH', '/home/mark/files.serialport.org/ieee802')

def get_documents():
    """Retrieve all processed documents from database"""
    conn = sqlite3.connect('ieee_docs.db')
    c = conn.cursor()
    
    c.execute('''SELECT filepath, filename, year, extension, filesize,
                        summary, subgroup, doc_number
                 FROM documents 
                 WHERE processed = 1
                 ORDER BY year, filename''')
    
    documents = []
    for row in c.fetchall():
        # Convert filepath to relative web path
        filepath = row[0].replace(BASE_PATH, '')
        web_path = filepath.replace('/docs', 'docs')
        
        documents.append({
            'filepath': web_path,
            'filename': row[1],
            'year': row[2],
            'extension': row[3],
            'filesize': row[4],
            'summary': row[5] or 'No summary available',
            'subgroup': row[6] or 'Unknown',
            'doc_number': row[7] or 'N/A'
        })
    
    conn.close()
    return documents

def generate_html(documents):
    """Generate static HTML index"""
    
    # Get unique subgroups for filter
    subgroups = sorted(set(doc['subgroup'] for doc in documents))
    
    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IEEE 802.1 Document Index (1994-1998)</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }}
        
        .header {{
            background: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        
        h1 {{
            margin: 0 0 10px 0;
            color: #333;
        }}
        
        .subtitle {{
            color: #666;
            font-size: 14px;
        }}
        
        .filters {{
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        
        .filter-group {{
            display: inline-block;
            margin-right: 20px;
        }}
        
        label {{
            font-weight: 600;
            margin-right: 10px;
            color: #333;
        }}
        
        select, input {{
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }}
        
        .table-container {{
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow-x: auto;
        }}
        
        table.dataTable {{
            width: 100% !important;
        }}
        
        .summary {{
            max-width: 500px;
            line-height: 1.4;
        }}
        
        .subgroup {{
            display: inline-block;
            padding: 4px 8px;
            background: #e3f2fd;
            border-radius: 3px;
            font-size: 12px;
            font-weight: 600;
            color: #1976d2;
        }}
        
        .year {{
            font-weight: 600;
            color: #666;
        }}
        
        .stats {{
            margin-top: 10px;
            color: #666;
            font-size: 14px;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>IEEE 802.1 Document Index</h1>
        <div class="subtitle">
            Early VLAN Development (1994-1998)
        </div>
        <div class="stats">
            Total Documents: {len(documents)} | 
            Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}
        </div>
    </div>
    
    <div class="filters">
        <div class="filter-group">
            <label for="subgroupFilter">Subgroup:</label>
            <select id="subgroupFilter">
                <option value="">All</option>
                {chr(10).join(f'<option value="{sg}">{sg}</option>' for sg in subgroups)}
            </select>
        </div>
        
        <div class="filter-group">
            <label for="yearFilter">Year:</label>
            <select id="yearFilter">
                <option value="">All</option>
                <option value="1994">1994</option>
                <option value="1995">1995</option>
                <option value="1996">1996</option>
                <option value="1997">1997</option>
                <option value="1998">1998</option>
            </select>
        </div>
        
        <div class="filter-group">
            <label for="typeFilter">Type:</label>
            <select id="typeFilter">
                <option value="">All</option>
                <option value=".pdf">PDF</option>
                <option value=".txt">TXT</option>
            </select>
        </div>
    </div>
    
    <div class="table-container">
        <table id="docTable" class="display">
            <thead>
                <tr>
                    <th>Year</th>
                    <th>Filename</th>
                    <th>Subgroup</th>
                    <th>Doc Number</th>
                    <th>Summary</th>
                    <th>Type</th>
                </tr>
            </thead>
            <tbody>
"""
    
    # Add table rows
    for doc in documents:
        filename_link = f'<a href="https://files.serialport.org/ieee802{doc["filepath"]}" target="_blank">{doc["filename"]}</a>'
        subgroup_badge = f'<span class="subgroup">{doc["subgroup"]}</span>'
        
        html += f"""
                <tr>
                    <td class="year">{doc['year']}</td>
                    <td>{filename_link}</td>
                    <td>{subgroup_badge}</td>
                    <td>{doc['doc_number']}</td>
                    <td class="summary">{doc['summary']}</td>
                    <td>{doc['extension']}</td>
                </tr>
"""
    
    html += """
            </tbody>
        </table>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {
            var table = $('#docTable').DataTable({
                pageLength: 50,
                order: [[0, 'asc'], [1, 'asc']],
                columnDefs: [
                    { width: "5%", targets: 0 },
                    { width: "25%", targets: 1 },
                    { width: "10%", targets: 2 },
                    { width: "15%", targets: 3 },
                    { width: "40%", targets: 4 },
                    { width: "5%", targets: 5 }
                ]
            });
            
            // Custom filtering
            $('#subgroupFilter, #yearFilter, #typeFilter').on('change', function() {
                var subgroup = $('#subgroupFilter').val();
                var year = $('#yearFilter').val();
                var type = $('#typeFilter').val();
                
                table
                    .column(2).search(subgroup)
                    .column(0).search(year)
                    .column(5).search(type)
                    .draw();
            });
        });
    </script>
</body>
</html>
"""
    
    return html

def main():
    print("IEEE 802.1 Index Generator")
    print("=" * 50)
    
    # Get documents
    documents = get_documents()
    
    if not documents:
        print("No processed documents found!")
        print("Run processor.py first to process documents.")
        return
    
    print(f"Found {len(documents)} processed documents")
    
    # Generate HTML
    html = generate_html(documents)
    
    # Write to file
    output_file = 'output/ieee802_index.html'
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html)
    
    print(f"\nIndex generated successfully!")
    print(f"Output file: {output_file}")
    print(f"\nOpen in browser: file://{os.path.abspath(output_file)}")
    print(f"Or copy to web directory and access via: https://files.serialport.org/ieee802/")

if __name__ == '__main__':
    import os
    main()
