import os
import time

from .api import send_structure


# Folders ignore karne ke liye
DENY_DIRS = {
    ".git",
    "node_modules",
    "venv",
    ".venv",
    "__pycache__",
    ".idea",
    ".vscode",
}

# Sirf ye file types bhejne hain
ALLOW_EXT = {
    ".py",
    ".js",
    ".ts",
    ".jsx",
    ".tsx",
    ".json",
    ".md",
    ".yml",
    ".yaml",
}


def is_allowed_file(filename: str) -> bool:
    return os.path.splitext(filename)[1] in ALLOW_EXT


def collect_structure(config):
    """
    Collect project file structure (metadata only).
    """

    files = []

    for root, dirs, filenames in os.walk(config.root):

        # Remove denied directories
        dirs[:] = [d for d in dirs if d not in DENY_DIRS]

        for name in filenames:

            if not is_allowed_file(name):
                continue

            full_path = os.path.join(root, name)

            try:
                size = os.path.getsize(full_path)
            except OSError:
                size = 0

            rel_path = os.path.relpath(
                full_path, config.root
            ).replace("\\", "/")

            files.append(
                {
                    "path": rel_path,
                    "size": size,
                }
            )

    return files


def push_structure_loop(config):
    """
    Periodically pushes file structure to backend.
    """

    while True:
        try:
            files = collect_structure(config)
            send_structure(config, files)
        except Exception:
            # SDK crash nahi hona chahiye
            pass

        time.sleep(10)