from __future__ import annotations

from django_anyllm.registry import ModelRegistry
from django_anyllm.settings import get_setting


DEFAULT_INSTRUCTIONS = """\
You are a helpful assistant with access to the Django models listed below.
Use the provided tools to query and manage data.

Guidelines:
- Always use the tools rather than guessing.
- Before creating or updating data, validate required fields using describe_model or get_model_schema.
- Use query_instances with filters and ordering to narrow results.
- When querying, respect the MAX_QUERY_LIMIT if no explicit limit is given.
"""


def build_system_prompt(registry: ModelRegistry | None = None, extra_instructions: str = "") -> str:
    """Build a system prompt that describes all registered models and their tools.

    Args:
        registry: The model registry to describe. Defaults to the global registry.
        extra_instructions: Additional text appended after the default instructions.

    Returns:
        A system prompt string suitable for the LLM.
    """
    from django_anyllm.registry import default_registry

    reg = registry or default_registry
    lines: list[str] = [DEFAULT_INSTRUCTIONS]

    setting_extra = get_setting("SYSTEM_PROMPT_EXTRA")
    if setting_extra:
        lines.append(setting_extra)

    if extra_instructions:
        lines.append(extra_instructions)

    models = reg.list_models()
    if models:
        lines.append("")
        lines.append("Registered Models:")
        for meta in models:
            lines.append(f"\n- {meta['app_label']}.{meta['model_name']}")
            if meta["verbose_name"]:
                lines.append(f"  verbose_name: {meta['verbose_name']}")
            if meta["docstring"]:
                lines.append(f"  description: {meta['docstring']}")
            lines.append(f"  permissions: {', '.join(meta['permissions'])}")

    lines.append("")
    lines.append(
        "Available tools: list_registered_models, describe_model, "
        "get_model_schema, query_instances, get_instance, create_instance, "
        "update_instance, delete_instance."
    )

    return "\n".join(lines)
