import os
import json
from typing import Dict, Any, List


class GroupManager:
    def __init__(self, script_groups_path: str):
        self.script_groups_path = script_groups_path

    def get_script_groups(self) -> List[Dict[str, Any]]:
        """Returns list of available script groups with their descriptions."""
        groups = []
        if not os.path.isdir(self.script_groups_path):
            print(
                f"Warning: Script groups directory not found: {self.script_groups_path}"
            )
            return []

        for d in os.listdir(self.script_groups_path):
            group_path = os.path.join(self.script_groups_path, d)
            if os.path.isdir(group_path):
                description = self._get_group_description(group_path)
                groups.append(
                    {
                        "id": d,
                        "name": description.get("name", d),
                        "description": description.get(
                            "description", "Sin descripción"
                        ),
                        "version": description.get("version", "1.0"),
                        "author": description.get("author", "Unknown"),
                    }
                )
        return groups

    def _get_group_description(self, group_path: str) -> Dict[str, Any]:
        """Get description for a script group."""
        description_file = os.path.join(group_path, "description.json")
        try:
            if os.path.exists(description_file):
                with open(description_file, "r", encoding="utf-8") as f:
                    return json.load(f)
        except Exception as e:
            print(f"Error reading group description from {description_file}: {e}")
        return {}
