"""Single entry point for aurora-lens.

Usage:
  aurora-lens demo [--model ...]      Run governance demo (requires API key)
  aurora-lens demo healthcare         Run healthcare governance demo (no API key)
  aurora-lens chat [--model ...]      Interactive chat with governance visibility
  aurora-lens batch --input FILE      Run governance over a JSONL scenario file
  aurora-lens proxy [-c config]       Run governed LLM proxy server
  aurora-lens                         Show help
"""

from __future__ import annotations

import argparse
import sys


def main(argv: list[str] | None = None) -> int:
    argv = argv if argv is not None else sys.argv[1:]

    parser = argparse.ArgumentParser(
        prog="aurora-lens",
        description="Governance substrate for LLM hallucination prevention.",
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # demo
    demo_parser = subparsers.add_parser("demo", help="Run governance demo")
    demo_parser.add_argument(
        "scenario",
        nargs="?",
        default=None,
        choices=["healthcare"],
        help="Demo scenario (omit for general demo requiring API key; 'healthcare' runs in-process, no API key needed)",
    )
    demo_parser.add_argument("--model", default="gpt-4o-mini", help="Model name (general demo only)")
    demo_parser.set_defaults(func=_run_demo)

    # chat
    chat_parser = subparsers.add_parser("chat", help="Interactive chat with governance visibility")
    chat_parser.add_argument("--model", default="gpt-4o-mini", help="Model name")
    chat_parser.set_defaults(func=_run_chat)

    # batch
    batch_parser = subparsers.add_parser(
        "batch",
        help="Run governance over a JSONL scenario file (requires API key)",
    )
    batch_parser.add_argument("--input", "-i", default="-",
                              help="Input JSONL path, or '-' for stdin")
    batch_parser.add_argument("--output", "-o", default="-",
                              help="Output JSONL path, or '-' for stdout")
    batch_parser.add_argument("--audit", "-a", default=None,
                              help="Forensic audit JSONL path")
    batch_parser.add_argument("--model", default="gpt-4o-mini",
                              help="LLM model name (default: gpt-4o-mini)")
    batch_parser.add_argument("--mode", default="enterprise",
                              choices=["enterprise", "public"],
                              help="Governance mode (default: enterprise)")
    batch_parser.add_argument("--fail-on-mismatch", action="store_true",
                              help="Exit 1 if any expected_action mismatch")
    batch_parser.set_defaults(func=_run_batch)

    # proxy
    proxy_parser = subparsers.add_parser("proxy", help="Run governed LLM proxy server")
    proxy_parser.add_argument("--config", "-c", default="aurora-lens.yaml", help="Config file path")
    proxy_parser.add_argument("--host", default=None, help="Listen host")
    proxy_parser.add_argument("--port", "-p", default=None, type=int, help="Listen port")
    proxy_parser.set_defaults(func=_run_proxy)

    args = parser.parse_args(argv)

    if args.command is None:
        parser.print_help()
        return 0

    return args.func(args)


def _run_demo(args: argparse.Namespace) -> int:
    if args.scenario == "healthcare":
        from aurora_lens.scripts.demo_healthcare import main as healthcare_main
        return healthcare_main()
    from aurora_lens.scripts.demo import main as demo_main
    # Pass through: --model
    pass_argv = []
    if args.model:
        pass_argv.extend(["--model", args.model])
    return demo_main(pass_argv)


def _run_chat(args: argparse.Namespace) -> int:
    from aurora_lens.scripts.chat import main as chat_main
    import asyncio
    return asyncio.run(chat_main(model=args.model))


def _run_batch(args: argparse.Namespace) -> int:
    from aurora_lens.scripts.batch import main as batch_main
    pass_argv = []
    for flag, val in [
        ("--input", args.input),
        ("--output", args.output),
        ("--model", args.model),
        ("--mode", args.mode),
    ]:
        pass_argv.extend([flag, val])
    if args.audit:
        pass_argv.extend(["--audit", args.audit])
    if args.fail_on_mismatch:
        pass_argv.append("--fail-on-mismatch")
    return batch_main(pass_argv)


def _run_proxy(args: argparse.Namespace) -> int:
    from aurora_lens.proxy.__main__ import main as proxy_main
    pass_argv = ["--config", args.config]
    if args.host is not None:
        pass_argv.extend(["--host", args.host])
    if args.port is not None:
        pass_argv.extend(["--port", str(args.port)])
    proxy_main(pass_argv)
    return 0  # uvicorn blocks; only reached on shutdown


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