"""
ONBOARDING_SETTINGS provider.

Injects onboarding status and settings context into LLM prompts
during conversational secret collection flows.
"""

import logging
from typing import Optional, Dict

from elizaos.runtime import AgentRuntime
from elizaos.types import Provider, Message


logger = logging.getLogger(__name__)


class OnboardingSettingsProvider(Provider):
    """
    Onboarding settings provider.

    Injects current onboarding state into the LLM context so the agent
    knows which settings need configuration and can guide the user.
    """

    name = "ONBOARDING_SETTINGS"
    description = "Current onboarding settings status for secrets collection"

    async def get(self, runtime: AgentRuntime, message: Message, state: Dict) -> Optional[str]:
        # Get room to determine context
        room = await runtime.get_room(message.room_id) if hasattr(message, "room_id") else None
        if not room:
            return None

        world_id = getattr(room, "world_id", None)
        if not world_id:
            return None

        is_dm = getattr(room, "type", "") == "DM"

        world = await runtime.get_world(world_id)
        if not world:
            return None

        metadata = getattr(world, "metadata", None)
        if not isinstance(metadata, dict):
            return None

        settings = metadata.get("settings")
        if not settings or not isinstance(settings, dict):
            if is_dm:
                return "No settings configured for this world."
            return None

        agent_name = getattr(runtime.character, "name", "Agent") if hasattr(runtime, "character") else "Agent"
        sender_name = state.get("senderName") if isinstance(state, dict) else None

        # Format settings
        entries = list(settings.items())
        formatted_settings = []
        required_unconfigured = 0

        for key, setting in entries:
            if isinstance(setting, dict):
                is_required = setting.get("required", False)
                value = setting.get("value")
                is_secret = setting.get("secret", False)
                name = setting.get("name", key)
                desc = setting.get("usageDescription") or setting.get("description", "")

                if value is None:
                    display_value = "Not set"
                    if is_required:
                        required_unconfigured += 1
                elif is_secret:
                    display_value = "****************"
                else:
                    display_value = str(value)

                label = "(Required)" if is_required else "(Optional)"
                formatted_settings.append(f"{key}: {display_value} {label}\n({name}) {desc}")

        settings_list = "\n\n".join(formatted_settings)
        valid_keys = f"Valid setting keys: {', '.join(k for k, _ in entries)}"

        if is_dm and required_unconfigured > 0:
            name = sender_name or "user"
            return (
                f"# PRIORITY TASK: Onboarding with {name}\n\n"
                f"{agent_name} needs to help the user configure "
                f"{required_unconfigured} required settings:\n\n"
                f"{settings_list}\n\n{valid_keys}\n\n"
                f"Instructions for {agent_name}:\n"
                f"- Only update settings if the user is clearly responding to a "
                f"setting you are currently asking about.\n"
                f"- If the user's reply clearly maps to a setting and a valid value, "
                f"you **must** call the UPDATE_SETTINGS action with the correct key and value.\n"
                f"- Never hallucinate settings or respond with values not listed above.\n"
                f"- Do not call UPDATE_SETTINGS just because onboarding started. "
                f"Only update when the user provides a specific value.\n"
                f"- Prioritize configuring required settings before optional ones."
            )

        if is_dm:
            return (
                f"All required settings have been configured. "
                f"Here's the current configuration:\n\n"
                f"{settings_list}\n\n{valid_keys}"
            )

        # Non-DM context
        if required_unconfigured > 0:
            warning = (
                f"IMPORTANT!: {required_unconfigured} required settings still need configuration. "
                f"{agent_name} should get onboarded with the OWNER as soon as possible.\n\n"
            )
        else:
            warning = "All required settings are configured.\n\n"

        return f"## Current Configuration\n\n{warning}{settings_list}"
