#!/usr/bin/env python3
"""Stage post-import automation files into the shared LAN scratch directory."""

import argparse
import shlex
import subprocess
import sys
from pathlib import Path


DEFAULT_TARGET = Path("/opt/lanscratch/redmine-post-import/repo")

PAYLOAD_PATHS = (
    "plugins",
    "docs",
    "semantic_index",
    "deploy",
    "dist",
    "post_import_refresh.py",
    "stage_post_import_payload.py",
    "reset_helpdesk_mail_settings.py",
    "validate_test_instance.py",
    "redmine_outbox_worker.py",
    "redMCP",
)

EXCLUDES = (
    ".env",
    ".venv",
    ".cache",
    "__pycache__/",
    "*.pyc",
    "*.tar.gz",
)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Copy the post-import automation payload into /opt/lanscratch."
    )
    parser.add_argument("--target", type=Path, default=DEFAULT_TARGET)
    parser.add_argument("--apply", action="store_true", help="Run rsync. Default is dry-run.")
    args = parser.parse_args()

    repo_root = Path(__file__).resolve().parent
    command = build_rsync_command(repo_root, args.target)
    if not args.apply:
        print("mode=dry-run")
        print(f"would run: mkdir -p {shlex.quote(str(args.target))}")
        print(f"would run: {command}")
        return 0

    args.target.mkdir(parents=True, exist_ok=True)
    print(f"running: {command}")
    result = subprocess.run(command, shell=True, check=False)
    return result.returncode


def build_rsync_command(repo_root: Path, target: Path) -> str:
    exclude_args = " ".join(f"--exclude {shlex.quote(pattern)}" for pattern in EXCLUDES)
    sources = " ".join(shlex.quote(str(repo_root / path)) for path in PAYLOAD_PATHS)
    return f"rsync -a --delete {exclude_args} {sources} {shlex.quote(str(target))}/"


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