#!/usr/bin/python3
"""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.backend import fetch_bibtex
from doi2bib3.io import save_bibtex_to_file


def build_parser():
    """Build the command-line parser."""
    p = argparse.ArgumentParser(
        description="Fetch BibTeX by DOI, DOI URL, arXiv id or arXiv URL"
    )
    p.add_argument(
        "identifier",
        nargs="?",
        help="DOI, DOI URL, arXiv id/URL, or publisher URL",
    )
    p.add_argument("-o", "--out", help="Write .bib file to this path")
    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 not args.identifier:
        parser.print_help()
        return 2

    try:
        bib = fetch_bibtex(args.identifier)
    except Exception as e:
        print("Error:", e, file=sys.stderr)
        return 1

    if args.out:
        save_bibtex_to_file(bib, args.out, append=True)
        print("Wrote", args.out)
    else:
        print(bib)
    return 0


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