#!/usr/bin/env python3.9
"""
Build docs: convert sdk/docs/*.md to sdk/website/docs/*.html

Usage:
    python3 build_docs.py

Requirements:
    pip install markdown
    # or: apt install python3-markdown
"""

import os
import sys
import re
from pathlib import Path

try:
    import markdown
    from markdown.extensions import fenced_code, tables, toc
except ImportError:
    print("ERROR: python-markdown is required.")
    print("Install: pip install markdown")
    sys.exit(1)

SCRIPT_DIR = Path(__file__).parent.resolve()
DOCS_DIR = SCRIPT_DIR.parent / "docs"
OUTPUT_DIR = SCRIPT_DIR / "docs"

CSS = """
:root {
    --bg-primary: #0a0e1a;
    --bg-secondary: #111827;
    --bg-card: #1a2035;
    --text-primary: #f0f4f8;
    --text-secondary: #94a3b8;
    --accent: #38bdf8;
    --accent-hover: #0ea5e9;
    --border: #1e293b;
    --code-bg: #0d1117;
}

* { margin: 0; padding: 0; box-sizing: border-box; }

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: var(--bg-primary);
    color: var(--text-primary);
    line-height: 1.7;
    font-size: 15px;
}

nav {
    background: rgba(10,14,26,0.9);
    backdrop-filter: blur(12px);
    border-bottom: 1px solid var(--border);
    padding: 0 24px;
    position: sticky;
    top: 0;
    z-index: 100;
}

.nav-inner {
    max-width: 1000px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 56px;
}

.nav-inner a {
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 0.9rem;
    font-weight: 500;
    transition: color 0.2s;
}

.nav-inner a:hover { color: var(--accent); }

.nav-title {
    font-size: 1.1rem;
    font-weight: 700;
    color: var(--text-primary) !important;
}

.container {
    max-width: 900px;
    margin: 0 auto;
    padding: 48px 24px;
}

.doc-content h1 {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border);
}

.doc-content h2 {
    font-size: 1.4rem;
    font-weight: 600;
    margin-top: 40px;
    margin-bottom: 16px;
    color: var(--accent);
}

.doc-content h3 {
    font-size: 1.1rem;
    font-weight: 600;
    margin-top: 28px;
    margin-bottom: 12px;
}

.doc-content p {
    margin-bottom: 14px;
    color: var(--text-secondary);
}

.doc-content p strong,
.doc-content li strong {
    color: var(--text-primary);
}

.doc-content a {
    color: var(--accent);
    text-decoration: none;
}

.doc-content a:hover {
    text-decoration: underline;
}

.doc-content code {
    background: var(--code-bg);
    color: #e2e8f0;
    padding: 2px 6px;
    border-radius: 4px;
    font-family: 'JetBrains Mono', 'Courier New', monospace;
    font-size: 0.85em;
    border: 1px solid var(--border);
}

.doc-content pre {
    background: var(--code-bg);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 16px;
    overflow-x: auto;
    margin: 16px 0;
}

.doc-content pre code {
    background: transparent;
    border: none;
    padding: 0;
    font-size: 0.85em;
    line-height: 1.6;
}

.doc-content ul, .doc-content ol {
    margin: 12px 0 12px 24px;
    color: var(--text-secondary);
}

.doc-content li {
    margin-bottom: 6px;
}

.doc-content table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    font-size: 0.9rem;
}

.doc-content th, .doc-content td {
    border: 1px solid var(--border);
    padding: 10px 14px;
    text-align: left;
}

.doc-content th {
    background: var(--bg-card);
    color: var(--accent);
    font-weight: 600;
}

.doc-content tr:nth-child(even) {
    background: rgba(255,255,255,0.02);
}

.doc-content blockquote {
    border-left: 3px solid var(--accent);
    margin: 16px 0;
    padding: 8px 16px;
    background: rgba(56,189,248,0.05);
    color: var(--text-secondary);
}

.doc-content hr {
    border: none;
    border-top: 1px solid var(--border);
    margin: 32px 0;
}

footer {
    text-align: center;
    padding: 32px 24px;
    border-top: 1px solid var(--border);
    color: var(--text-secondary);
    font-size: 0.85rem;
}

@media (max-width: 768px) {
    .container { padding: 24px 16px; }
    .doc-content h1 { font-size: 1.5rem; }
}
"""

HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title} - LLUAV SDK Docs</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>{css}</style>
</head>
<body>
<nav>
  <div class="nav-inner">
    <a href="index.html" class="nav-title">🚁 LLUAV SDK</a>
    <div>
      <a href="index.html">首页</a>
      <a href="index.html#docs">文档</a>
    </div>
  </div>
</nav>
<div class="container">
  <div class="doc-content">
{content}
  </div>
</div>
<footer>
  <p>LLUAV Developer SDK &copy; 2026. MIT License.</p>
</footer>
</body>
</html>
"""


def md_to_html(md_path: Path, out_path: Path):
    md_text = md_path.read_text(encoding="utf-8")

    # Convert .md links to .html links
    md_text = re.sub(r'\[([^\]]+)\]\(([^)]+)\.md\)', r'[\1](\2.html)', md_text)

    md = markdown.Markdown(extensions=[
        'fenced_code',
        'tables',
        'toc',
    ])
    html_body = md.convert(md_text)

    title = md_path.stem.replace('_', ' ').replace('-', ' ').title()
    if md_path.name == 'PROTOCOL.md':
        title = 'Protocol Specification'
    elif md_path.name == 'API_REFERENCE.md':
        title = 'API Reference'
    elif md_path.name == 'ARCHITECTURE.md':
        title = 'Architecture'
    elif md_path.name == 'TROUBLESHOOTING.md':
        title = 'Troubleshooting'
    elif md_path.name == 'CHANGELOG.md':
        title = 'Changelog'

    full_html = HTML_TEMPLATE.format(
        title=title,
        css=CSS,
        content=html_body
    )

    out_path.write_text(full_html, encoding="utf-8")
    print(f"  ✓ {md_path.name} -> {out_path.name}")


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    md_files = sorted(DOCS_DIR.glob("*.md"))
    if not md_files:
        print("No markdown files found in", DOCS_DIR)
        sys.exit(1)

    print(f"Building docs from {DOCS_DIR} -> {OUTPUT_DIR}")
    for md_file in md_files:
        html_file = OUTPUT_DIR / (md_file.stem + ".html")
        md_to_html(md_file, html_file)

    print(f"\nDone. Generated {len(md_files)} HTML pages.")


if __name__ == '__main__':
    main()
