#!/usr/bin/env python3
"""Convert BibTeX files to numbered markdown reference lists.\n
Reads one or more .bib files and writes corresponding .md files with
numbered references.  Each entry becomes a line of the form:\n
    1. **Title**, Authors, *Journal* **Volume**, Pages (Year)
       [arXiv:XXXX.XXXXX](https://arxiv.org/abs/XXXX.XXXXX)\n
Fields that are absent are omitted.  Conference proceedings use *booktitle*
instead of *journal*.\n
Usage:
    python scripts/convert_bibtex_to_markdown.py input.bib [input2.bib ...]
"""

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

from bibtex_lib import (
    parse_bibtex_to_entries,
    strip_outer_braces,
    entries_to_markdown_list,
)

# Backward-compatible aliases for scripts that import the old private names.
_parse_entries = parse_bibtex_to_entries
_strip_braces = strip_outer_braces

def main() -> None:
    """Parse CLI arguments and convert .bib files to markdown reference lists."""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("inputs", nargs="+", help="Input .bib file(s)")
    args = parser.parse_args()
    for bib_path in args.inputs:
        if not bib_path.endswith(".bib"):
            parser.error(f"input file must be a .bib file: {bib_path}")
        if not os.path.isfile(bib_path):
            parser.error(f"input file not found: {bib_path}")
    #
    for bib_path in args.inputs:
        md_path = os.path.splitext(bib_path)[0] + ".md"
        with open(bib_path) as f:
            bib = f.read()
        entries = parse_bibtex_to_entries(bib)
        if not entries:
            print(f"No BibTeX entries found in {bib_path}.", file=sys.stderr)
            continue
        md = entries_to_markdown_list(entries)
        with open(md_path, "w") as f:
            f.write(md)
        print(f"Wrote {len(entries)} references to {md_path}", file=sys.stderr)

if __name__ == "__main__":
    main()
