import os

BLOCKED_FILES = {
    ".env",
    ".env.production",
    ".env.prod",
    "secrets.yaml",
    "credentials.json",
    ".gitignore",
}

BLOCKED_EXTENSIONS = {".pem", ".key", ".p12"}

SKIP_DIRS = {
    "tests", "test", "__pycache__", "node_modules",
    "dist", "build", ".venv", "venv", "migrations", ".git",
}

SKIP_EXTENSIONS = {".lock", ".log", ".md", ".txt", ".d.ts"}

MAX_FILE_SIZE = 50 * 1024  # 50kb


def is_blocked(file_path: str) -> bool:
    """Return True if this file must never be sent."""
    name = os.path.basename(file_path)
    _, ext = os.path.splitext(name)
    return name in BLOCKED_FILES or ext in BLOCKED_EXTENSIONS


def collect_files(repo_path: str = ".") -> tuple[str, list[str]]:
    """Walk repo_path, collect relevant files, and return a single bundled string."""
    print(f"Scanning repo: {repo_path}\n")
    bundle = []
    collected_paths = []
    skipped = []

    for root, dirs, files in os.walk(repo_path):
        dirs[:] = [
            d for d in dirs
            if d not in SKIP_DIRS and not d.startswith(".")
        ]

        for filename in sorted(files):
            full_path = os.path.join(root, filename)
            rel_path = os.path.relpath(full_path, repo_path)
            _, ext = os.path.splitext(filename)

            if is_blocked(full_path):
                skipped.append((rel_path, "blocked"))
                continue

            if ext in SKIP_EXTENSIONS:
                skipped.append((rel_path, "skipped extension"))
                continue

            try:
                size = os.path.getsize(full_path)
            except Exception as e:
                print(f"  Error checking size of {rel_path}: {e}")
                continue

            if size > MAX_FILE_SIZE:
                skipped.append((rel_path, f"too large ({size // 1024}kb)"))
                continue

            try:
                with open(full_path, "r", encoding="utf-8") as f:
                    content = f.read()
            except Exception as e:
                print(f"  Error reading {rel_path}: {e}")
                continue

            bundle.append(f"### {rel_path}\n{content}")
            collected_paths.append(rel_path)

    # Summary
    print(f"Collected ({len(bundle)} files):")
    for path in collected_paths:
        print(f"  + {path}")

    print(f"\nSkipped ({len(skipped)} files):")
    for path, reason in skipped:
        print(f"  - {path}  [{reason}]")

    if not bundle:
        print("\nNo files collected.")
        return "", []

    print(f"\nDone.")
    return "\n\n".join(bundle), collected_paths
