"""Command-line interface for the LAPIS converter."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from lapis_spec import __version__
from lapis_spec.converter import convert_to_string
from lapis_spec.parser.openapi_loader import OpenAPILoadError, load_openapi


def build_parser() -> argparse.ArgumentParser:
    """Build and return the argument parser."""
    parser = argparse.ArgumentParser(
        prog="lapis",
        description="Convert OpenAPI 3.0/3.1 specifications to LAPIS format.",
    )
    parser.add_argument(
        "-i",
        "--input",
        required=True,
        help="Path to the OpenAPI file (.json, .yaml, .yml)",
    )
    parser.add_argument(
        "-o",
        "--output",
        required=True,
        help="Path to the output .lapis file",
    )
    parser.add_argument(
        "--no-validate",
        action="store_true",
        default=False,
        help="Skip OpenAPI schema validation",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    """Entry point for the ``lapis`` CLI command.

    Returns 0 on success, 1 on error.
    """
    parser = build_parser()
    args = parser.parse_args(argv)

    input_path = Path(args.input)
    output_path = Path(args.output)

    try:
        doc = load_openapi(input_path, skip_validation=args.no_validate)
    except OpenAPILoadError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1

    try:
        lapis_text = convert_to_string(doc)
    except Exception as exc:
        print(f"Conversion error: {exc}", file=sys.stderr)
        return 1

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(lapis_text, encoding="utf-8")
    print(f"Written {output_path}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
