#!/usr/bin/env python3
"""
Import Obsidian vault markdown files into BookStack via REST API.
Converts basic Markdown to HTML. Tags secret pages with 'dm-only'.

Usage: python3 import-obsidian-to-bookstack.py <vault_path> <api_url> <token_id> <token_secret>
"""
import os, re, json, requests, sys

API_KEY = sys.argv[3] + ":" + sys.argv[4]
BASE_URL = sys.argv[2] + "/api"
VAULT_PATH = sys.argv[1]
HEADERS = {"Authorization": f"Token {API_KEY}", "Content-Type": "application/json"}

def md_to_html(text):
    """Basic markdown to HTML conversion."""
    code_blocks = {}
    def save_code(m):
        key = f"__CODE_BLOCK_{len(code_blocks)}__"
        code_blocks[key] = m.group(0)
        return key
    text = re.sub(r'```.*?```', save_code, text, flags=re.DOTALL)
    text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)
    text = re.sub(r'^#{6} (.+)$', r'<h6>\1</h6>', text, flags=re.MULTILINE)
    text = re.sub(r'^#{5} (.+)$', r'<h5>\1</h5>', text, flags=re.MULTILINE)
    text = re.sub(r'^#{4} (.+)$', r'<h4>\1</h4>', text, flags=re.MULTILINE)
    text = re.sub(r'^#{3} (.+)$', r'<h3>\1</h3>', text, flags=re.MULTILINE)
    text = re.sub(r'^#{2} (.+)$', r'<h2>\1</h2>', text, flags=re.MULTILINE)
    text = re.sub(r'^# (.+)$', r'<h1>\1</h1>', text, flags=re.MULTILINE)
    text = re.sub(r'\*\*\*(.+?)\*\*\*', r'<strong><em>\1</em></strong>', text)
    text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
    text = re.sub(r'\*(.+?)\*', r'<em>\1</em>', text)
    text = re.sub(r'\[\[[^\]|]+\|([^\]]+)\]\]', r'\1', text)
    text = re.sub(r'\[\[([^\]]+)\]\]', r'\1', text)
    text = re.sub(r'\[([^\]]+)\]\(([^\)]+)\)', r'<a href="\2">\1</a>', text)
    text = re.sub(r'^>\s*(.+)$', r'<blockquote>\1</blockquote>', text, flags=re.MULTILINE)
    text = re.sub(r'^---+$', r'<hr>', text, flags=re.MULTILINE)
    # Basic paragraphs
    text = re.sub(r'\n\n+', '</p>\n<p>', text)
    text = '<p>' + text + '</p>'
    text = re.sub(r'<p>\s*</p>', '', text)
    for key, val in code_blocks.items():
        text = text.replace(key, val)
    return text

def create_page(book_id, name, html, tags=None):
    payload = {"book_id": book_id, "name": name, "html": html, "tags": [{"name": t, "value": ""} for t in (tags or [])]}
    r = requests.post(f"{BASE_URL}/pages", headers=HEADERS, json=payload, timeout=15)
    if r.status_code in (200, 201):
        d = r.json()
        print(f"  Created: {name} (id={d.get('id')})")
        return d.get('id')
    else:
        print(f"  FAILED {r.status_code}: {name} - {r.text[:200]}")
        return None

if __name__ == "__main__":
    print("Import vault files here. Add your own STARTER_PUBLIC / STARTER_SECRET lists.")
