#!/usr/bin/env python3
"""Convert BibTeX files to HTML ordered reference lists.\n
Reads one or more .bib files and writes corresponding .html files with
numbered references.  Each entry becomes an <li> with title, authors,
venue, year, and arXiv/doi links.\n
Usage:
    python scripts/convert_bibtex_to_html.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,
    entries_to_html_document,
)

def main() -> None:
    """Parse CLI arguments and convert .bib files to HTML 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:
        html_path = os.path.splitext(bib_path)[0] + ".html"
        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
        html = entries_to_html_document(entries, title=os.path.basename(html_path))
        with open(html_path, "w") as f:
            f.write(html)
        print(f"Wrote {len(entries)} references to {html_path}", file=sys.stderr)

if __name__ == "__main__":
    main()
