#!python
"""Forward explicit DRA export invocations to ``daylily-ec export``."""

from __future__ import annotations

import argparse
import os
import shutil
import sys
from pathlib import Path


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cluster", "--cluster-name", dest="cluster_name")
    parser.add_argument("--fsx-file-system-id")
    parser.add_argument("--source-path", required=True)
    parser.add_argument("--destination-s3-uri", required=True)
    parser.add_argument("--region", required=True)
    parser.add_argument("--profile")
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--verbose", action="store_true")
    return parser


def _resolve_entrypoint() -> list[str]:
    cli = shutil.which("daylily-ec")
    if cli:
        return [cli]

    repo_root = Path(__file__).resolve().parents[1]
    if (repo_root / "daylily_ec" / "__main__.py").is_file():
        os.chdir(repo_root)
        return [sys.executable, "-m", "daylily_ec"]

    raise SystemExit("Error: daylily-ec is not available. Run 'source ./activate' first.")


def main(argv: list[str] | None = None) -> int:
    args = _build_parser().parse_args(argv)
    cmd = [
        *_resolve_entrypoint(),
        "export",
        "--source-path",
        args.source_path,
        "--destination-s3-uri",
        args.destination_s3_uri,
        "--region",
        args.region,
        "--output-dir",
        str(Path(args.output_dir).expanduser()),
    ]
    if args.cluster_name:
        cmd.extend(["--cluster-name", args.cluster_name])
    if args.fsx_file_system_id:
        cmd.extend(["--fsx-file-system-id", args.fsx_file_system_id])
    if args.profile:
        cmd.extend(["--profile", args.profile])
    if args.verbose:
        cmd.append("--verbose")

    os.execvp(cmd[0], cmd)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
