#!/usr/bin/env python3
# Copyright (c) 2017-2026 Juancarlo Añez (apalala@gmail.com)
# SPDX-License-Identifier: BSD-4-Clause
from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path

# Generated by Gemini - January 24, 2026
# Credits: Gemini

# --- Project Configuration ---
SPHINX_DIR = Path('./docs')
MKDOCS_DIR = Path('./mkdocs/docs')


def migrate_tatsu_docs():
    """
    Batch converts TatSu .rst documentation to .md for MkDocs.
    Maintains directory structure and copies non-rst assets.
    """
    # 1. Verify Pandoc
    try:
        subprocess.run(["pandoc", "--version"], capture_output=True, check=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("Error: Pandoc not found. Install via brew/apt before running.")
        sys.exit(1)

    if not SPHINX_DIR.exists():
        print(f"Error: Sphinx source directory '{SPHINX_DIR}' does not exist.")
        return

    # 2. Prepare Destination
    MKDOCS_DIR.mkdir(parents=True, exist_ok=True)

    # 3. Process all files in the source directory
    # rglob('*') gets everything including subdirectories
    all_files = list(SPHINX_DIR.rglob('*'))

    print(f"Processing {len(all_files)} items from {SPHINX_DIR}...")

    for item in all_files:
        if item.is_dir():
            continue

        # Determine the relative path to maintain hierarchy
        rel_path = item.relative_to(SPHINX_DIR)
        dest_path = MKDOCS_DIR / rel_path

        # Ensure the destination subdirectory exists
        dest_path.parent.mkdir(parents=True, exist_ok=True)

        if item.suffix.lower() == '.rst':
            # Convert .rst to .md
            md_dest = dest_path.with_suffix('.md')
            print(f"Converting: {rel_path} -> {md_dest.relative_to(MKDOCS_DIR)}")

            try:
                subprocess.run(
                    [
                        "pandoc",
                        str(item),
                        "-f",
                        "rst",
                        "-t",
                        "commonmark_x",
                        "--wrap=none",
                        "-o",
                        str(md_dest),
                    ],
                    check=True,
                )
            except subprocess.CalledProcessError as e:
                print(f"Failed to convert {item}: {e}")
        else:
            # Copy assets (images, static files, etc.)
            print(f"Copying asset: {rel_path}")
            shutil.copy2(item, dest_path)

    print("-" * 30)
    print(f"Success! Documentation migrated to: {MKDOCS_DIR.absolute()}")
    print("Next step: Run 'uv run mkdocs serve' to verify the build.")


if __name__ == "__main__":
    migrate_tatsu_docs()
