"""CLI entry point for ``test-runner capture``."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="test-capture",
        description="Capture test cases baselines from a source database.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("--project-root", type=Path, default=Path.cwd())
    parser.add_argument("--source-connection", type=str, default=None)
    parser.add_argument("--baseline-dir", type=Path, default=None)
    parser.add_argument("-c", "--connection", type=str, default=None, dest="snowflake_connection")
    parser.add_argument("-w", "--watch", action="store_true", default=False)
    parser.add_argument("-q", "--quiet", action="store_true", default=False)
    return parser


def main(argv: list[str] | None = None) -> None:
    from test_runner.common.container import create_container
    from .runner import run_capture

    parser = _build_parser()
    args = parser.parse_args(argv)

    try:
        container = create_container(
            str(args.project_root),
            source_connection=args.source_connection,
            target_connection=args.snowflake_connection,
        )
        stats = run_capture(
            config=container.config(),
            factory_registry=container.factory_registry(),
            project_root=args.project_root,
            baseline_dir=args.baseline_dir,
            snowflake_connection=args.snowflake_connection,
        )
    except (FileNotFoundError, ValueError) as exc:
        print(f"Error: {exc}", file=sys.stderr)
        sys.exit(1)

    sys.exit(stats.failed)


if __name__ == "__main__":
    main()
