#!/usr/bin/env python3
"""
Convert RST files to Markdown using pandoc.
"""

import subprocess
import sys
from pathlib import Path


def convert_file(rst_path, md_path=None):
    """Convert a single RST file to Markdown using pandoc."""
    rst_path = Path(rst_path)
    if md_path is None:
        md_path = rst_path.with_suffix('.md')
    else:
        md_path = Path(md_path)

    subprocess.run(
        ['pandoc', '-f', 'rst', '-t', 'gfm', '-o', str(md_path), str(rst_path)],
        check=True
    )
    return md_path


def convert_output_directory(output_dir):
    """Convert all index.rst files in output directory to index.md."""
    output_path = Path(output_dir)
    count = 0

    for rst_file in output_path.rglob('index.rst'):
        md_file = rst_file.with_suffix('.md')
        try:
            convert_file(rst_file, md_file)
            count += 1
        except subprocess.CalledProcessError as e:
            print(f"Warning: Failed to convert {rst_file}: {e}")

    return count


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: rst2md.py <output_directory>")
        print("       rst2md.py <file.rst> [output.md]")
        sys.exit(1)

    path = Path(sys.argv[1])

    if path.is_dir():
        count = convert_output_directory(path)
        print(f"Converted {count} RST files to Markdown")
    elif path.is_file():
        output = sys.argv[2] if len(sys.argv) > 2 else None
        md_path = convert_file(path, output)
        print(f"Converted {path} -> {md_path}")
    else:
        print(f"Error: {path} not found")
        sys.exit(1)
