#!/usr/bin/env python3
"""
Markdown to DokuWiki Converter
Converts Markdown documentation to DokuWiki syntax for homelab documentation mirror
"""

import re
import os
import sys
import requests
from pathlib import Path
from urllib.parse import quote

class MarkdownToDokuWiki:
    def __init__(self, dokuwiki_base_url="http://atlantis.vish.local:8399"):
        self.dokuwiki_base_url = dokuwiki_base_url

    def convert_markdown_to_dokuwiki(self, markdown_content):
        """Convert Markdown content to DokuWiki syntax"""
        content = markdown_content

        # Convert headers
        content = re.sub(r'^# (.*?)$', r'====== \1 ======', content, flags=re.MULTILINE)
        content = re.sub(r'^## (.*?)$', r'===== \1 =====', content, flags=re.MULTILINE)
        content = re.sub(r'^### (.*?)$', r'==== \1 ====', content, flags=re.MULTILINE)
        content = re.sub(r'^#### (.*?)$', r'=== \1 ===', content, flags=re.MULTILINE)
        content = re.sub(r'^##### (.*?)$', r'== \1 ==', content, flags=re.MULTILINE)

        # Convert bold and italic
        content = re.sub(r'\*\*(.*?)\*\*', r'**\1**', content)  # Bold (already correct)
        content = re.sub(r'\*(.*?)\*', r'//\1//', content)      # Italic

        # Convert code blocks
        content = re.sub(r'^```(\w+)?\n(.*?)^```', r'<code \1>\n\2</code>', content, flags=re.MULTILINE | re.DOTALL)
        content = re.sub(r'`([^`]+)`', r'%%\1%%', content)  # Inline code

        # Convert lists
        content = re.sub(r'^- (.*?)$', r'  * \1', content, flags=re.MULTILINE)
        content = re.sub(r'^\d+\. (.*?)$', r'  - \1', content, flags=re.MULTILINE)

        # Convert links
        content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'[[\2|\1]]', content)

        # Convert tables (basic conversion)
        lines = content.split('\n')
        converted_lines = []
        in_table = False

        for line in lines:
            if '|' in line and line.strip().startswith('|'):
                if not in_table:
                    in_table = True
                # Convert table row
                cells = [cell.strip() for cell in line.split('|')[1:-1]]
                converted_line = '^ ' + ' ^ '.join(cells) + ' ^' if '---' not in line else None
                if converted_line and '---' not in line:
                    # Check if this is a header row (next line might be separator)
                    converted_lines.append(converted_line)
            elif in_table and line.strip() == '':
                in_table = False
                converted_lines.append(line)
            else:
                in_table = False
                converted_lines.append(line)

        content = '\n'.join(converted_lines)

        # Convert checkboxes
        content = re.sub(r'- \[x\] (.*?)$', r'  * ✅ \1', content, flags=re.MULTILINE)
        content = re.sub(r'- \[ \] (.*?)$', r'  * ☐ \1', content, flags=re.MULTILINE)

        # Convert blockquotes
        content = re.sub(r'^> (.*?)$', r'> \1', content, flags=re.MULTILINE)

        return content

    def create_dokuwiki_page(self, page_id, content, summary="Updated from repository"):
        """Create or update a DokuWiki page via HTTP POST"""
        try:
            # DokuWiki edit URL
            edit_url = f"{self.dokuwiki_base_url}/doku.php"

            # Prepare form data for page creation/update
            form_data = {
                'id': page_id,
                'do': 'save',
                'wikitext': content,
                'summary': summary,
                'minor': '1'
            }

            # Make the request
            response = requests.post(edit_url, data=form_data, timeout=30)

            if response.status_code == 200:
                print(f"✅ Successfully created/updated page: {page_id}")
                return True
            else:
                print(f"❌ Failed to create page {page_id}: HTTP {response.status_code}")
                return False

        except Exception as e:
            print(f"❌ Error creating page {page_id}: {str(e)}")
            return False

    def convert_file(self, markdown_file_path, dokuwiki_page_id):
        """Convert a single Markdown file and upload to DokuWiki"""
        try:
            with open(markdown_file_path, 'r', encoding='utf-8') as f:
                markdown_content = f.read()

            # Convert to DokuWiki syntax
            dokuwiki_content = self.convert_markdown_to_dokuwiki(markdown_content)

            # Add header with source information
            header = f"""====== {os.path.basename(markdown_file_path)} ======

//This page is automatically mirrored from the homelab Git repository//
//Last updated: {os.path.getmtime(markdown_file_path)}//
//Source: {markdown_file_path}//

"""

            dokuwiki_content = header + dokuwiki_content

            # Create the page in DokuWiki
            success = self.create_dokuwiki_page(dokuwiki_page_id, dokuwiki_content)

            return success

        except Exception as e:
            print(f"❌ Error converting file {markdown_file_path}: {str(e)}")
            return False

def main():
    converter = MarkdownToDokuWiki()

    # Define key documentation files to convert
    docs_to_convert = [
        {
            'file': '/home/homelab/organized/repos/homelab/README.md',
            'page_id': 'homelab:readme'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/docs/INDEX.md',
            'page_id': 'homelab:docs:index'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/docs/admin/GITOPS_COMPREHENSIVE_GUIDE.md',
            'page_id': 'homelab:docs:admin:gitops_comprehensive_guide'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/DOCUMENTATION_AUDIT_REPORT.md',
            'page_id': 'homelab:documentation_audit_report'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/docs/infrastructure/INFRASTRUCTURE_HEALTH_REPORT.md',
            'page_id': 'homelab:docs:infrastructure:health_report'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/docs/runbooks/add-new-service.md',
            'page_id': 'homelab:docs:runbooks:add_new_service'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/GITOPS_DEPLOYMENT_GUIDE.md',
            'page_id': 'homelab:gitops_deployment_guide'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/OPERATIONAL_STATUS.md',
            'page_id': 'homelab:operational_status'
        },
        {
            'file': '/home/homelab/organized/repos/homelab/MONITORING_ARCHITECTURE.md',
            'page_id': 'homelab:monitoring_architecture'
        }
    ]

    print("🚀 Starting Markdown to DokuWiki conversion...")

    successful_conversions = 0
    total_conversions = len(docs_to_convert)

    for doc in docs_to_convert:
        file_path = doc['file']
        page_id = doc['page_id']

        if os.path.exists(file_path):
            print(f"\n📄 Converting: {file_path} -> {page_id}")
            if converter.convert_file(file_path, page_id):
                successful_conversions += 1
        else:
            print(f"⚠️  File not found: {file_path}")

    print(f"\n🎯 Conversion Summary:")
    print(f"✅ Successful: {successful_conversions}/{total_conversions}")
    print(f"❌ Failed: {total_conversions - successful_conversions}/{total_conversions}")

    if successful_conversions > 0:
        print(f"\n🌐 DokuWiki pages available at:")
        print(f"   {converter.dokuwiki_base_url}/doku.php?id=homelab:readme")
        print(f"   {converter.dokuwiki_base_url}/doku.php?id=homelab:docs:index")

if __name__ == "__main__":
    main()
