from __future__ import annotations

import argparse
import importlib.resources as resources
import os
import shutil
from pathlib import Path


def copy_tree(src: Path, dst: Path) -> None:
    dst.mkdir(parents=True, exist_ok=True)
    for item in src.iterdir():
        target = dst / item.name
        if item.is_dir():
            copy_tree(item, target)
        elif not target.exists():
            shutil.copy2(item, target)


def ensure_symlink(target: Path, link_path: Path) -> None:
    if link_path.exists() or link_path.is_symlink():
        return
    rel_target = os.path.relpath(target, start=link_path.parent)
    link_path.symlink_to(rel_target)


def run_setup() -> None:
    cwd = Path.cwd()
    agents_dir = cwd / ".agents"
    template_dir = resources.files("divami_agents").joinpath("templates/.agents")
    with resources.as_file(template_dir) as materialized:
        copy_tree(Path(materialized), agents_dir)
    ensure_symlink(agents_dir / "main.md", cwd / "agents.md")
    print("Installed .agents and linked agents.md")


def main() -> None:
    parser = argparse.ArgumentParser(prog="divami-agents")
    subparsers = parser.add_subparsers(dest="command", required=True)
    subparsers.add_parser("setup")
    args = parser.parse_args()
    if args.command == "setup":
        run_setup()
