"""CLI entrypoints for installing packaged agentic assets."""

from __future__ import annotations

import shutil
import sys
from importlib import resources
from importlib.resources import as_file
from pathlib import Path

import agentic_toolbelt

PAYLOAD_ITEMS = (".agents", ".codex", "AGENTS.md")


def copy_payload(destination: Path, force: bool = False) -> tuple[list[str], list[str]]:
    """Copy packaged payload items to ``destination``.

    Returns two lists: copied item names and skipped item names.
    """

    copied: list[str] = []
    skipped: list[str] = []

    temp_root = destination / ".agentic_set_tmp"

    try:
        with as_file(resources.files(agentic_toolbelt)) as source_root:
            for item_name in PAYLOAD_ITEMS:
                source_path = source_root / item_name
                if not source_path.exists():
                    raise FileNotFoundError(f"Missing packaged payload item: {item_name}")

                destination_path = destination / item_name
                if destination_path.exists():
                    if not force:
                        skipped.append(item_name)
                        continue

                    if destination_path.is_dir() and not destination_path.is_symlink():
                        shutil.rmtree(destination_path)
                    else:
                        destination_path.unlink()

                if source_path.is_dir():
                    temp_path = temp_root / item_name
                    if temp_path.exists():
                        shutil.rmtree(temp_path)
                    temp_path.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copytree(source_path, temp_path)
                    temp_path.replace(destination_path)
                else:
                    destination_path.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(source_path, destination_path)

                copied.append(item_name)
    finally:
        if temp_root.exists():
            shutil.rmtree(temp_root)

    return copied, skipped


def build_parser() -> "argparse.ArgumentParser":
    import argparse

    parser = argparse.ArgumentParser(
        prog="agentic-set",
        description="Copy packaged .agents/.codex/AGENTS.md into a directory.",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Overwrite existing files/directories if they already exist.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    destination = Path.cwd()
    destination.mkdir(parents=True, exist_ok=True)

    try:
        copied, skipped = copy_payload(destination, force=args.force)
    except Exception as exc:  # pragma: no cover - exercised via CLI behavior
        print(f"agentic-set: {exc}", file=sys.stderr)
        return 1

    for item in copied:
        print(f"copied {item} -> {destination / item}")
    for item in skipped:
        print(f"skipped {item} (already exists; use --force to overwrite)")

    return 0


if __name__ == "__main__":  # pragma: no cover
    raise SystemExit(main())
