from __future__ import annotations

from django.apps import apps
from django.db import models


class ModelIntrospectionService:
    """Introspects Django models for auto-import and field inspection."""

    @staticmethod
    def get_all_models() -> dict[str, type[models.Model]]:
        """Return a dict mapping model class names to model classes.

        This replicates the shell_plus auto-import behaviour —
        all registered Django models are available by their class name.
        """
        model_dict: dict[str, type[models.Model]] = {}
        for model in apps.get_models():
            model_dict[model.__name__] = model
        return model_dict

    @staticmethod
    def get_model_fields(model: type[models.Model]) -> list[dict[str, str]]:
        """Return a list of dicts with 'name', 'type', and 'column' for each field."""
        fields = []
        for field in model._meta.get_fields():
            field_info: dict[str, str] = {
                "name": field.name,
                "type": type(field).__name__,
            }
            if hasattr(field, "column"):
                field_info["column"] = field.column
            fields.append(field_info)
        return fields

    @staticmethod
    def get_field_value(instance: models.Model, field_name: str) -> object:
        """Safely retrieve a field value from a model instance."""
        return getattr(instance, field_name, None)

    @staticmethod
    def get_instance_display_data(instance: models.Model) -> list[tuple[str, str, str]]:
        """Return a list of (field_name, field_type, value) tuples for display."""
        data = []
        for field in instance._meta.get_fields():
            if hasattr(field, "column") or hasattr(field, "attname"):
                value = getattr(instance, field.name, "N/A")
                data.append((field.name, type(field).__name__, repr(value)))
        return data

