"""
Data handling for CRD data.
Follows the custom/generated split from servala.core.crd.forms.
"""

from servala.core.crd.utils import deslugify


def get_value_from_path(data, path):
    """
    Get a value from nested dict using dot notation path.
    e.g., 'spec.parameters.size.disk' from {'spec': {'parameters': {'size': {'disk': '10Gi'}}}}
    """
    parts = path.split(".")
    current = data
    for part in parts:
        if isinstance(current, dict) and part in current:
            current = current[part]
        else:
            return None
    return current


def get_form_config_fieldsets(spec, form_config, name):
    full_data = {"spec": spec, "name": name}
    fieldsets = []
    for fieldset_config in form_config.get("fieldsets", []):
        fields = []
        for field_config in fieldset_config.get("fields", []):
            mapping = field_config.get("controlplane_field_mapping", "")
            # Skip the name field as it's shown in the header
            if mapping == "name":
                continue

            value = get_value_from_path(full_data, mapping)
            if value is None:
                continue

            label = field_config.get("label") or deslugify(mapping.split(".")[-1])

            fields.append(
                {
                    "key": mapping,
                    "label": label,
                    "value": value,
                    "help_text": field_config.get("help_text", ""),
                }
            )

        if fields:
            fieldsets.append(
                {
                    "title": fieldset_config.get("title", "Configuration"),
                    "fields": fields,
                    "fieldsets": {},
                }
            )

    return fieldsets


def get_auto_generated_fieldsets(spec):
    """
    Auto-generate fieldsets from spec structure (fallback when no form_config).
    Excludes "General" tab - only returns nested structures.
    """
    nested_fieldsets = {}

    # First pass: organize fields into nested structures
    for key, value in spec.items():
        if isinstance(value, dict):
            # This is a nested structure
            if key not in nested_fieldsets:
                nested_fieldsets[key] = {
                    "title": deslugify(key),
                    "fields": [],
                    "fieldsets": {},
                }

            # Process fields in the nested structure
            for sub_key, sub_value in value.items():
                if isinstance(sub_value, dict):
                    # Even deeper nesting
                    if sub_key not in nested_fieldsets[key]["fieldsets"]:
                        nested_fieldsets[key]["fieldsets"][sub_key] = {
                            "title": deslugify(sub_key),
                            "fields": [],
                        }

                    # Add fields from the deeper level
                    for leaf_key, leaf_value in sub_value.items():
                        nested_fieldsets[key]["fieldsets"][sub_key]["fields"].append(
                            {
                                "key": leaf_key,
                                "label": deslugify(leaf_key),
                                "value": leaf_value,
                            }
                        )
                else:
                    # Add field to parent level
                    nested_fieldsets[key]["fields"].append(
                        {
                            "key": sub_key,
                            "label": deslugify(sub_key),
                            "value": sub_value,
                        }
                    )

    # Second pass: Promote fields based on count
    for group_key, group in list(nested_fieldsets.items()):
        # Promote single sub-fieldsets to parent
        for sub_key, sub_fieldset in list(group["fieldsets"].items()):
            if len(sub_fieldset["fields"]) == 1:
                field = sub_fieldset["fields"][0]
                field["label"] = f"{sub_fieldset['title']}: {field['label']}"
                group["fields"].append(field)
                del group["fieldsets"][sub_key]

        # Remove empty groups
        total_fields = len(group["fields"])
        for sub_fieldset in group["fieldsets"].values():
            total_fields += len(sub_fieldset["fields"])

        if total_fields == 0:
            del nested_fieldsets[group_key]

    # Create fieldsets from the organized data (no "General" tab)
    fieldsets = []
    for group in nested_fieldsets.values():
        fieldsets.append(group)

    return fieldsets


def get_nested_data(instance):
    """
    Organize spec data into fieldsets.
    Uses form_config when available, otherwise auto-generates from spec structure.
    """
    if not instance.spec:
        return []
    if (
        instance.context
        and instance.context.service_definition
        and instance.context.service_definition.form_config
    ):
        return get_form_config_fieldsets(
            instance.spec, instance.context.service_defintion.form_config, instance.name
        )

    return get_auto_generated_fieldsets(instance.spec)
