# ruff: noqa: T201
"""Module for setting up Yera provider configuration and credentials."""

from typing import Literal

from yera.config2.dataclasses import YeraConfig
from yera.config2.read import read_config
from yera.config2.setup_handlers.anthropic import AnthropicSetup
from yera.config2.setup_handlers.aws_bedrock import BedrockSetup
from yera.config2.setup_handlers.azure import AzureSetup
from yera.config2.setup_handlers.llama_cpp import LlamaCppSetup
from yera.config2.setup_handlers.ollama import OllamaSetup
from yera.config2.setup_handlers.openai import OpenAISetup
from yera.config2.write import write_config

handlers = {
    "anthropic": AnthropicSetup(),
    "openai": OpenAISetup(),
    "ollama": OllamaSetup(),
    "azure": AzureSetup(),
    "llama-cpp": LlamaCppSetup(),
    "bedrock": BedrockSetup(),
}


def setup(
    location: Literal["global", "local"],
    auto_import: bool,
) -> None:
    """Set up Yera provider configuration and credentials.

    Configures model provider credentials by either automatically importing from
    environment variables or prompting the user interactively. The configuration is
    saved to the specified location and credentials are saved to the secure developer
    keyring.

    Args:
        location: Where to save the configuration - "global" for user-wide
            settings (~/.config/yera/config.toml) or "local" for project-specific
            settings (./yera.toml)
        auto_import: If True, automatically import credentials from environment
            variables and only prompt for providers that fail auto-import. If False,
            prompt interactively for all providers.

    The function will:
        1. Load existing config from the specified location (or create new)
        2. Attempt auto-import if enabled, falling back to interactive prompt
        3. Allow user to configure additional providers from a menu
        4. Save the merged configuration to the specified location
    """
    try:
        config = read_config(use_global=location == "global")
    except FileNotFoundError:
        config = YeraConfig()

    to_ask = []

    if auto_import:
        for k, handler in handlers.items():
            new_config = handler.automatic_setup()
            if new_config:
                config = config.merge(new_config)
            else:
                print(f"Could not find credentials for {k}")
                to_ask.append(k)
    else:
        to_ask = list(handlers.keys())

    user_has_quit = False
    while not user_has_quit:
        if len(to_ask) == 0:
            break

        print(f"There are {len(to_ask)} other providers you can set up")
        sep = "\n * "
        print(sep + sep.join(f"{i + 1}: {name}" for i, name in enumerate(to_ask)))

        print("\nOr you can enter 0 to finish.")
        ix = input(" > ")
        if ix == "0":
            break
        handler = handlers[to_ask[int(ix) - 1]]
        new_config = handler.interactive_setup()
        config = config.merge(new_config)

        del to_ask[int(ix) - 1]

    write_config(config, location, True)


def set_default_llm(location: Literal["global", "local"]) -> None:
    """Interactive user flow to choose a default LLM for your configuration.

    Args:
        location: which config to read and update: global or local.

    """
    config = read_config(use_global=location == "global")

    labels = [v.id for v in config.models.llm.values()]
    print(f"You have {len(labels)} models to choose from:\n * ")
    print("\n * ".join(labels))
    print("Please enter your choice of default llm:")
    choice = input(" > ")
    while choice not in labels:
        print(f"{choice} not in list. Please try again")
        choice = input(" > ")

    config.defaults.models.llm = choice
    write_config(config, location, True)
    print("Config updated.")
