#!/usr/bin/env python3
"""Convert a markdown file to a styled HTML file for the vault index."""
import re, sys, os

def md_to_html(md_text):
    lines = md_text.split('\n')
    html_lines = []
    in_table = False
    in_list = False
    list_items = []
    i = 0
    while i < len(lines):
        line = lines[i]
        if not line.strip():
            if in_table:
                html_lines.append('</table>')
                in_table = False
            if in_list and list_items:
                html_lines.append('<ul>' + ''.join(list_items) + '</ul>')
                list_items = []
                in_list = False
            html_lines.append('')
            i += 1
            continue
        if line.startswith('# '):
            if in_table: html_lines.append('</table>'); in_table = False
            if in_list and list_items: html_lines.append('<ul>' + ''.join(list_items) + '</ul>'); list_items = []; in_list = False
            html_lines.append(f'<h1>{line[2:]}</h1>')
            i += 1; continue
        if line.startswith('## '):
            if in_table: html_lines.append('</table>'); in_table = False
            if in_list and list_items: html_lines.append('<ul>' + ''.join(list_items) + '</ul>'); list_items = []; in_list = False
            html_lines.append(f'<h2>{line[3:]}</h2>')
            i += 1; continue
        if line.startswith('### '):
            if in_table: html_lines.append('</table>'); in_table = False
            if in_list and list_items: html_lines.append('<ul>' + ''.join(list_items) + '</ul>'); list_items = []; in_list = False
            html_lines.append(f'<h3>{line[4:]}</h3>')
            i += 1; continue
        if line.startswith('#### '):
            if in_table: html_lines.append('</table>'); in_table = False
            if in_list and list_items: html_lines.append('<ul>' + ''.join(list_items) + '</ul>'); list_items = []; in_list = False
            html_lines.append(f'<h4>{line[5:]}</h4>')
            i += 1; continue
        if line.startswith('|') and not in_list:
            if not in_table:
                html_lines.append('<table>')
                in_table = True
            cells = [c.strip() for c in line.split('|')[1:-1]]
            if all(c.replace('-', '').replace(' ', '') == '' for c in cells):
                i += 1; continue
            tag = 'th' if not html_lines or html_lines[-1] == '<table>' else 'td'
            html_lines.append('<tr>' + ''.join(f'<{tag}>{c}</{tag}>' for c in cells) + '</tr>')
            i += 1; continue
        if line.startswith('- ') or line.startswith('* '):
            if in_table: html_lines.append('</table>'); in_table = False
            item_text = line[2:]
            item_text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', item_text)
            list_items.append(f'<li>{item_text}</li>')
            in_list = True
            i += 1; continue
        m = re.match(r'^(\d+)\.\s+(.+)$', line)
        if m:
            if in_table: html_lines.append('</table>'); in_table = False
            item_text = m.group(2)
            item_text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', item_text)
            list_items.append(f'<li>{item_text}</li>')
            in_list = True
            i += 1; continue
        if in_list and list_items:
            html_lines.append('<ul>' + ''.join(list_items) + '</ul>')
            list_items = []
            in_list = False
        if in_table:
            html_lines.append('</table>')
            in_table = False
        text = line.strip()
        text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
        text = re.sub(r'`(.+?)`', r'<code>\1</code>', text)
        html_lines.append(f'<p>{text}</p>')
        i += 1
    if in_list and list_items:
        html_lines.append('<ul>' + ''.join(list_items) + '</ul>')
    if in_table:
        html_lines.append('</table>')
    return '\n'.join(html_lines)


def slugify(name):
    return name.replace('-', ' ').title()


if __name__ == '__main__':
    md_path = sys.argv[1]
    name = os.path.splitext(os.path.basename(md_path))[0]
    with open(md_path, 'r') as f:
        md = f.read()
    body = md_to_html(md)
    html = f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{slugify(name)} — Motion Canvas</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            color: #333;
            line-height: 1.7;
        }}
        .container {{ max-width: 900px; margin: 0 auto; padding: 40px 20px; }}
        header {{
            background: #0B1120;
            color: white;
            padding: 40px 0;
            margin-bottom: 40px;
        }}
        header h1 {{ font-size: 1.8rem; margin-bottom: 8px; }}
        header p {{ opacity: 0.7; font-size: 0.95rem; }}
        header a {{ color: #E8893A; text-decoration: none; }}
        .section {{ margin-bottom: 50px; }}
        h1 {{ font-size: 1.6rem; color: #0B1120; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 2px solid #E8893A; }}
        h2 {{ font-size: 1.3rem; color: #0B1120; margin: 30px 0 12px; }}
        h3 {{ font-size: 1.1rem; color: #0B1120; margin: 20px 0 8px; }}
        h4 {{ font-size: 1rem; color: #333; margin: 15px 0 6px; }}
        p {{ margin-bottom: 12px; color: #444; }}
        ul, ol {{ margin: 10px 0 15px 25px; }}
        li {{ margin-bottom: 6px; color: #444; }}
        strong {{ color: #0B1120; }}
        code {{
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.9em;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }}
        th, td {{
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background: #0B1120;
            color: white;
            font-weight: 600;
        }}
        tr:nth-child(even) {{ background: #fafafa; }}
        .back-link {{
            display: inline-block;
            margin-bottom: 20px;
            color: #2563EB;
            text-decoration: none;
        }}
        .back-link:hover {{ text-decoration: underline; }}
        footer {{
            text-align: center;
            padding: 30px 0;
            color: #999;
            font-size: 0.85rem;
        }}
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>{slugify(name)}</h1>
            <p><a href="../index.html">Back to Vault Index</a></p>
        </div>
    </header>
    <div class="container">
        {body}
    </div>
    <footer>
        <p>Motion Canvas · Generated 2026-08-15 · Synced via Syncthing</p>
    </footer>
</body>
</html>'''
    out_path = md_path.replace('.md', '.html')
    with open(out_path, 'w') as f:
        f.write(html)
    print(f'Wrote {out_path}')
