#!/usr/bin/env python3
#
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
"""HRW4U script - Process HRW4U input and produce output (AST or HRW)."""

from __future__ import annotations

import argparse
import os
from importlib.metadata import PackageNotFoundError, version as _pkg_version
from pathlib import Path
from typing import Any

from hrw4u.hrw4uLexer import hrw4uLexer
from hrw4u.hrw4uParser import hrw4uParser
from hrw4u.visitor import HRW4UVisitor
from hrw4u.common import run_main
from hrw4u.sandbox import SandboxConfig


def _package_version() -> str:
    try:
        return _pkg_version("apple-hrw4u")
    except PackageNotFoundError:
        return "unknown"


def _add_args(parser: argparse.ArgumentParser, output_group: argparse._MutuallyExclusiveGroup) -> None:
    parser.add_argument("--version", action="version", version=f"hrw4u {_package_version()}")
    output_group.add_argument(
        "--output",
        choices=["hrw", "hrw4u"],
        default="hrw",
        help="Output format: hrw (header_rewrite, default) or hrw4u (expand procedures inline)")
    parser.add_argument(
        "--procedures-path",
        metavar="DIR[:DIR...]",
        dest="procedures_path",
        default="",
        help="Colon-separated list of directories to search for procedure files")
    parser.add_argument("--sandbox", metavar="FILE", type=Path, help="Path to sandbox YAML configuration file")


def _visitor_kwargs(args: argparse.Namespace) -> dict[str, Any]:
    kwargs: dict[str, Any] = {}
    if args.procedures_path:
        kwargs['proc_search_paths'] = [Path(p) for p in args.procedures_path.split(os.pathsep) if p]
    if args.sandbox:
        kwargs['sandbox'] = SandboxConfig.load(args.sandbox)
    return kwargs


def main() -> None:
    """Main entry point for the hrw4u script."""
    run_main(
        description="Process HRW4U input and produce output (AST or HRW).",
        lexer_class=hrw4uLexer,
        parser_class=hrw4uParser,
        visitor_class=HRW4UVisitor,
        error_prefix="hrw4u",
        output_flag_name="hrw",
        output_flag_help="Produce the HRW output (default)",
        add_args=_add_args,
        visitor_kwargs=_visitor_kwargs)


if __name__ == "__main__":
    main()
