#!python
"""Command-line interface script for doi2bib3.

When executed directly from the repository tree (e.g. ``python3 scripts/doi2bib3``),
prefer the repository copy of the package over any system-installed one by
inserting the repository root into ``sys.path`` before importing.
"""
import argparse
import os
import sys

# Ensure local repo package is preferred when running the script from the
# repository root (so testing modified code is straightforward).
try:
    # scripts/ is inside the repo; repo root is parent directory
    repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if repo_root not in sys.path:
        sys.path.insert(0, repo_root)
except Exception:
    pass

from doi2bib3 import __version__, fetch_bibtex, format_bibtex_to_aps_bibitem
from doi2bib3.io import save_bibtex_to_file


def get_version():
    """Return the version bundled with the package."""
    return __version__


def build_parser():
    """Build the command-line parser."""
    current_version = get_version()
    p = argparse.ArgumentParser(
        description=(
            f"%(prog)s {current_version}\n\n"
            "Fetch BibTeX by DOI, DOI URL, arXiv id or arXiv URL"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument("--version", action="version", version=f"%(prog)s {current_version}")
    p.add_argument(
        "identifier",
        nargs="?",
        help="DOI, DOI URL, arXiv id/URL, or publisher URL",
    )
    p.add_argument(
        "-i", "--input", help="Text file with one identifier per line ('#' comments allowed)"
    )
    p.add_argument("-o", "--out", "--output", help="Write .bib file to this path")
    p.add_argument(
        "-b",
        "--bibitem",
        action="store_true",
        help="Also print an APS/RevTeX \\bibitem entry derived from the BibTeX",
    )
    p.add_argument(
        "-m",
        "--mbox",
        action="store_true",
        help="Wrap author surnames in \\mbox{} to prevent line breaks",
    )
    return p


def main(argv=None):
    """Run CLI: resolve identifier, fetch normalized BibTeX, output or save."""
    parser = build_parser()
    args = parser.parse_args(argv)
    if args.identifier and args.input:
        parser.error("use either an identifier or --input, not both")
    if args.input:
        try:
            with open(args.input, encoding="utf-8") as fh:
                identifiers = [s for s in map(str.strip, fh) if s and not s.startswith("#")]
        except OSError as e:
            print("Error:", e, file=sys.stderr)
            return 1
    elif args.identifier:
        identifiers = [args.identifier]
    else:
        parser.print_help()
        return 2

    status = 0
    wrote_output = False
    for identifier in identifiers:
        try:
            bib = fetch_bibtex(identifier, mbox=args.mbox)
        except Exception as e:
            print(f"Error ({identifier}):" if args.input else "Error:", e, file=sys.stderr)
            status = 1
            continue

        if args.out:
            # Write the first successful result fresh so a previous run's
            # output is not kept; only append further results of this run.
            save_bibtex_to_file(bib, args.out, append=wrote_output)
            wrote_output = True
            print("Wrote", args.out)
        else:
            print(bib)

        if args.bibitem:
            try:
                print(format_bibtex_to_aps_bibitem(bib, mbox=args.mbox))
            except Exception as e:
                print("Warning: failed to format bibitem:", e, file=sys.stderr)

    return status


if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))
