from fnmatch import fnmatch
from pathlib import Path

try:
    import tomllib
except ModuleNotFoundError:  # pragma: no cover - exercised on Python < 3.11
    import tomli as tomllib

from setuptools import find_packages, setup


PACKAGE_DIR = Path(__file__).parent / "agentic_toolbelt"
PYPROJECT_FILE = Path(__file__).parent / "pyproject.toml"
README_FILE = Path(__file__).parent / "README.md"
PAYLOAD_ROOTS = (".agents", ".codex", ".github", ".tasks", "templates", "AGENTS.md")
EXCLUDED_PATTERNS = (
    "__pycache__/*",
    "*.pyc",
    "*.pyo",
    ".codex/skills/dev-browser/node_modules/*",
)


def _project_metadata():
    with PYPROJECT_FILE.open("rb") as fh:
        return tomllib.load(fh)["project"]


def _package_version():
    return _project_metadata()["version"]


def _data_files():
    files = []
    for root_name in PAYLOAD_ROOTS:
        root_path = PACKAGE_DIR / root_name
        if root_path.is_file():
            rel_path = root_path.relative_to(PACKAGE_DIR)
            files.append(str(rel_path))
            continue

        for path in sorted(root_path.rglob("*")):
            if not path.is_file():
                continue

            rel_path = path.relative_to(PACKAGE_DIR)
            rel_path_str = str(rel_path)
            if any(fnmatch(rel_path_str, pattern) for pattern in EXCLUDED_PATTERNS):
                continue

            files.append(rel_path_str)
    return files


def main():
    project = _project_metadata()
    setup(
        name="agentic-toolbelt",
        version=project["version"],
        description=project["description"],
        python_requires=project["requires-python"],
        long_description=README_FILE.read_text(encoding="utf-8"),
        long_description_content_type="text/markdown",
        packages=find_packages(),
        include_package_data=True,
        package_data={"agentic_toolbelt": _data_files()},
        entry_points={
            "console_scripts": [
                "agentic-set=agentic_toolbelt.cli:main",
            ]
        },
    )


if __name__ == "__main__":
    main()
