import os

ALLOWED_EXTENSIONS = {
    ".py", ".html", ".css", ".js",
    ".txt", ".md", ".json",
    ".jsx", ".tsx", ".dart",
    ".java", ".c", ".cpp", ".h",
    ".xml", ".yml", ".yaml"
}

IGNORE_FOLDERS = {"venv", "__pycache__", ".git", "node_modules"}


def get_tree(root_folder):
    tree_lines = []
    for root, dirs, files in os.walk(root_folder):
        dirs[:] = [d for d in dirs if d not in IGNORE_FOLDERS]

        level = root.replace(root_folder, "").count(os.sep)
        indent = "│   " * level
        folder_name = os.path.basename(root)

        if level == 0:
            tree_lines.append(folder_name + "/")
        else:
            tree_lines.append(f"{indent}├── {folder_name}/")

        sub_indent = "│   " * (level + 1)
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext in ALLOWED_EXTENSIONS:
                tree_lines.append(f"{sub_indent}├── {file}")
    return "\n".join(tree_lines)


def export_project():
    root_folder = os.getcwd()
    folder_name = os.path.basename(root_folder)
    output_file = os.path.join(root_folder, f"{folder_name}.txt")

    with open(output_file, "w", encoding="utf-8") as out:
        out.write(get_tree(root_folder))
        out.write("\n\n")

        for root, dirs, files in os.walk(root_folder):
            dirs[:] = [d for d in dirs if d not in IGNORE_FOLDERS]

            for file in files:
                ext = os.path.splitext(file)[1]
                if ext in ALLOWED_EXTENSIONS:
                    file_path = os.path.join(root, file)
                    relative_path = os.path.relpath(file_path, root_folder)

                    out.write("=" * 50 + "\n")
                    out.write(relative_path + "\n")
                    out.write("=" * 50 + "\n")

                    try:
                        with open(file_path, "r", encoding="utf-8") as f:
                            out.write(f.read())
                    except:
                        out.write("[Could not read this file]\n")

                    out.write("\n\n")

    print(f"✅ codesnap created: {output_file}")


def main():
    export_project()