#!/usr/bin/env python3
"""
NEOG OS - Markdown to HTML Converter
Converts Markdown text to styled HTML pages
"""

import re
from datetime import datetime

def markdown_to_html(markdown_text):
    """Convert Markdown to HTML with NEOG styling"""

    html = markdown_text

    # Headers
    html = re.sub(r'^### (.*?)$', r'<h3>\1</h3>', html, flags=re.MULTILINE)
    html = re.sub(r'^## (.*?)$', r'<h2>\1</h2>', html, flags=re.MULTILINE)
    html = re.sub(r'^# (.*?)$', r'<h1>\1</h1>', html, flags=re.MULTILINE)

    # Bold and italic
    html = re.sub(r'\*\*\*(.+?)\*\*\*', r'<strong><em>\1</em></strong>', html)
    html = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', html)
    html = re.sub(r'\*(.+?)\*', r'<em>\1</em>', html)
    html = re.sub(r'\_\_(.+?)\_\_', r'<strong>\1</strong>', html)
    html = re.sub(r'\_(.+?)\_', r'<em>\1</em>', html)

    # Code blocks
    html = re.sub(r'```(\w+)?\n(.*?)```', r'<pre><code class="language-\1">\2</code></pre>', html, flags=re.DOTALL)
    html = re.sub(r'`([^`]+)`', r'<code>\1</code>', html)

    # Links
    html = re.sub(r'\[([^\]]+)\]\(([^\)]+)\)', r'<a href="\2" target="_blank">\1</a>', html)

    # Blockquotes
    html = re.sub(r'^> (.+)$', r'<blockquote>\1</blockquote>', html, flags=re.MULTILINE)

    # Horizontal rules
    html = re.sub(r'^---$', r'<hr>', html, flags=re.MULTILINE)
    html = re.sub(r'^━━━.*$', r'<hr class="thick">', html, flags=re.MULTILINE)

    # Lists (unordered)
    html = re.sub(r'^\- (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)
    html = re.sub(r'^\* (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)
    html = re.sub(r'((<li>.*</li>\n?)+)', r'<ul>\1</ul>', html, flags=re.DOTALL)

    # Lists (ordered)
    html = re.sub(r'^\d+\. (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)

    # Tables (simple Markdown tables)
    html = convert_tables(html)

    # Paragraphs (lines not already in tags)
    lines = html.split('\n')
    processed_lines = []
    for line in lines:
        stripped = line.strip()
        if stripped and not re.match(r'^<[a-z]', stripped):
            processed_lines.append(f'<p>{line}</p>')
        else:
            processed_lines.append(line)

    html = '\n'.join(processed_lines)

    # Clean up empty paragraphs
    html = re.sub(r'<p>\s*</p>', '', html)

    return html

def convert_tables(text):
    """Convert Markdown tables to HTML"""
    lines = text.split('\n')
    result = []
    in_table = False
    table_lines = []

    for line in lines:
        if '|' in line and not in_table:
            in_table = True
            table_lines = [line]
        elif '|' in line and in_table:
            table_lines.append(line)
        elif in_table:
            # End of table
            result.append(render_table(table_lines))
            table_lines = []
            in_table = False
            result.append(line)
        else:
            result.append(line)

    # Handle table at end of text
    if in_table:
        result.append(render_table(table_lines))

    return '\n'.join(result)

def render_table(lines):
    """Render a Markdown table as HTML"""
    if len(lines) < 2:
        return '\n'.join(lines)

    # Remove separator line (line with dashes)
    lines = [l for l in lines if not re.match(r'^\|[\s\-:|]+\|$', l)]

    if not lines:
        return ''

    html = ['<table>']

    # Header row
    headers = [cell.strip() for cell in lines[0].strip('|').split('|')]
    html.append('<thead><tr>')
    for header in headers:
        html.append(f'<th>{header}</th>')
    html.append('</tr></thead>')

    # Body rows
    if len(lines) > 1:
        html.append('<tbody>')
        for line in lines[1:]:
            cells = [cell.strip() for cell in line.strip('|').split('|')]
            html.append('<tr>')
            for cell in cells:
                html.append(f'<td>{cell}</td>')
            html.append('</tr>')
        html.append('</tbody>')

    html.append('</table>')
    return '\n'.join(html)

def generate_html_page(markdown_content, title=None):
    """Generate complete HTML page from Markdown content"""

    if title is None:
        title = f"NEOG Page - {datetime.now().strftime('%Y-%m-%d %H:%M')}"

    # Convert markdown to HTML
    content_html = markdown_to_html(markdown_content)

    # Generate full HTML page
    html_template = f"""<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            background: #000;
            color: #00ff41;
            font-family: 'Monaco', 'Courier New', monospace;
            line-height: 1.6;
            padding: 20px;
        }}

        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(0, 20, 0, 0.3);
            padding: 40px;
            border: 2px solid #00ff41;
            border-radius: 8px;
        }}

        h1 {{
            color: #00ff41;
            font-size: 2.5em;
            margin-bottom: 20px;
            text-shadow: 0 0 20px #00ff41;
            border-bottom: 2px solid #00ff41;
            padding-bottom: 10px;
        }}

        h2 {{
            color: #00d9ff;
            font-size: 2em;
            margin-top: 30px;
            margin-bottom: 15px;
            text-shadow: 0 0 15px #00d9ff;
        }}

        h3 {{
            color: #00ffaa;
            font-size: 1.5em;
            margin-top: 25px;
            margin-bottom: 10px;
        }}

        p {{
            margin: 10px 0;
            color: #00ff41;
        }}

        strong {{
            color: #00ffff;
            font-weight: bold;
        }}

        em {{
            color: #00d9ff;
            font-style: italic;
        }}

        code {{
            background: rgba(0, 255, 65, 0.1);
            color: #00ffff;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Monaco', monospace;
        }}

        pre {{
            background: rgba(0, 255, 65, 0.05);
            border: 1px solid #00ff41;
            border-radius: 5px;
            padding: 15px;
            overflow-x: auto;
            margin: 15px 0;
        }}

        pre code {{
            background: none;
            padding: 0;
        }}

        blockquote {{
            border-left: 4px solid #00ff41;
            padding-left: 20px;
            margin: 15px 0;
            color: #00d9ff;
            font-style: italic;
        }}

        hr {{
            border: none;
            border-top: 1px solid #00ff41;
            margin: 30px 0;
        }}

        hr.thick {{
            border-top: 2px solid #00ff41;
        }}

        ul, ol {{
            margin: 15px 0;
            padding-left: 40px;
        }}

        li {{
            margin: 8px 0;
            color: #00ff41;
        }}

        a {{
            color: #00d9ff;
            text-decoration: none;
            border-bottom: 1px solid #00d9ff;
            transition: all 0.3s;
        }}

        a:hover {{
            color: #00ffff;
            border-bottom-color: #00ffff;
            text-shadow: 0 0 10px #00ffff;
        }}

        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: rgba(0, 255, 65, 0.05);
        }}

        th, td {{
            border: 1px solid #00ff41;
            padding: 12px;
            text-align: left;
        }}

        th {{
            background: rgba(0, 255, 65, 0.2);
            color: #00ffff;
            font-weight: bold;
        }}

        td {{
            color: #00ff41;
        }}

        tr:hover {{
            background: rgba(0, 255, 65, 0.1);
        }}

        .timestamp {{
            text-align: right;
            color: #00d9ff;
            font-size: 0.9em;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #00ff41;
        }}

        .header-banner {{
            background: rgba(0, 255, 65, 0.1);
            border: 2px solid #00ff41;
            padding: 20px;
            margin-bottom: 30px;
            border-radius: 8px;
            text-align: center;
        }}

        .success {{ color: #00ff41; }}
        .info {{ color: #00d9ff; }}
        .warning {{ color: #ffaa00; }}
        .error {{ color: #ff0041; }}
    </style>
</head>
<body>
    <div class="container">
        {content_html}

        <div class="timestamp">
            <p>📄 Generated by NEOG OS on {datetime.now().strftime('%Y-%m-%d at %H:%M:%S')}</p>
            <p>🤖 Neural Enhanced Operating Grid</p>
        </div>
    </div>
</body>
</html>"""

    return html_template

if __name__ == "__main__":
    # Test the converter
    sample_markdown = """
# Test Page

## Introduction

This is a **test page** created with *Markdown*.

### Features

- Bullet points
- **Bold text**
- `Inline code`

### Code Example

```python
def hello():
    print("Hello NEOG!")
```

### Table

| Component | Status |
|-----------|--------|
| Server | ✅ Active |
| Dashboard | ✅ Running |

> This is a blockquote

---

**End of test**
"""

    html = generate_html_page(sample_markdown, "Test Page")
    print(html)
