# backend/core/group_settings_manager.py
from pathlib import Path
import json
from typing import Dict, Any
from datetime import datetime
import os


class GroupSettingsManager:
    """Manages settings for script groups"""

    def __init__(self, script_groups_dir: Path):
        self.script_groups_dir = script_groups_dir
        self.config_schema = self._load_config_schema()

    def _load_config_schema(self) -> Dict[str, Any]:
        """Load the main configuration schema for script groups"""
        schema_file = self.script_groups_dir / "config.json"
        try:
            with open(schema_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading group config schema: {e}")
            return {
                "config_schema": {
                    "work_dir": {
                        "type": "string",
                        "description": "Working directory for this script group",
                        "required": True,
                    },
                    "description": {
                        "type": "string",
                        "description": "Description of this script group",
                        "default": "",
                    },
                }
            }

    def _validate_setting(
        self, key: str, value: Any, field_schema: Dict[str, Any]
    ) -> Any:
        """Validate and convert a single setting value"""
        field_type = field_schema.get("type")

        if value is None or value == "":
            if field_schema.get("required", False):
                raise ValueError(f"Field '{key}' is required")
            return field_schema.get("default")

        try:
            if field_type == "string":
                return str(value)
            elif field_type == "number":
                return float(value) if "." in str(value) else int(value)
            elif field_type == "boolean":
                if isinstance(value, str):
                    return value.lower() == "true"
                return bool(value)
            elif field_type == "directory":
                path = Path(value)
                if not path.is_absolute():
                    path = Path(self.script_groups_dir) / path
                if not path.exists():
                    path.mkdir(parents=True, exist_ok=True)
                return str(path)
            else:
                return value
        except Exception as e:
            raise ValueError(f"Invalid value for field '{key}': {str(e)}")

    def get_group_settings(self, group_id: str) -> Dict[str, Any]:
        """Get settings for a specific script group"""
        settings_file = self.script_groups_dir / group_id / "group.json"

        if settings_file.exists():
            try:
                with open(settings_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except Exception as e:
                print(f"Error loading group settings: {e}")

        return {
            "work_dir": "",
            "description": "",
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat(),
        }

    def update_group_settings(self, group_id: str, settings: Dict[str, Any]):
        """Update settings for a specific script group"""
        schema = self.config_schema.get("config_schema", {})
        validated_settings = {}

        # Validate each setting against schema
        for key, field_schema in schema.items():
            if key in settings:
                validated_settings[key] = self._validate_setting(
                    key, settings[key], field_schema
                )
            elif field_schema.get("required", False):
                raise ValueError(f"Required field '{key}' is missing")
            else:
                validated_settings[key] = field_schema.get("default")

        # Add non-schema fields
        for key, value in settings.items():
            if key not in schema:
                validated_settings[key] = value

        # Update timestamps
        validated_settings["updated_at"] = datetime.now().isoformat()

        group_dir = self.script_groups_dir / group_id
        settings_file = group_dir / "group.json"

        if not settings_file.exists():
            validated_settings["created_at"] = validated_settings["updated_at"]
            group_dir.mkdir(parents=True, exist_ok=True)

        # Save settings
        with open(settings_file, "w", encoding="utf-8") as f:
            json.dump(validated_settings, f, indent=4)