import typer
from importlib.metadata import version

from archo.config import (
    config_exists, setup_config, get_config,
    get_provider, update_provider,
    get_model, update_model,
    get_api_key, update_api_key,
    get_llm_host, update_llm_host,
)
from archo.llm.llm_client import call_llm
from archo.collector.file_collector import collect_files
from archo.output.output_generator import write_output

app = typer.Typer()

def version_callback(value: bool):
    if value:
        typer.echo(f"archo {version('archo')}")
        raise typer.Exit()

@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context,
    version: bool = typer.Option(None, "--version", "-v", callback=version_callback, is_eager=True, help="Show version and exit."),
):
    """
    Sets up archo for the first time if .archo/config doesn't exist
    Reads in all the files in the current working directory ignoring sensitive files
    Sends those files to be interpreted by the LLM of your choice and return a structured response
    An ARCHO.md file is created with a high level overview of the application's architecture
    """
    if ctx.invoked_subcommand or version:
        return

    if not config_exists():
        init()

    file_string, file_list = collect_files()

    if file_string:
        provider_name = get_provider()

        user_response = typer.prompt(f"The following files will be sent to {provider_name}: {file_list}\nWould you like to continue? [y/n]")

        if user_response.lower() == "n" or user_response.lower() == "no":
            typer.echo("Aborting.")
            raise typer.Exit()

        model_name = get_model()
        llm_host_value = get_llm_host()
        api_key_value = get_api_key()
        result = call_llm(file_string, provider_name, model_name, api_key_value, llm_host_value)
        write_output(result)

@app.command()
def init():
    """
    Sets up .archo/config for the first time.
    Prompts user for provider, model and API Key
    Prompts user OLLAMA_HOST if provider is ollama
    Adds ./archo to .gitignore if it's not already there
    """

    if config_exists():
        typer.echo("Config file already exists. Run archo --help for available commands.")
        raise typer.Exit(1)

    typer.echo("Welcome to Archo! Let's get you set up.")

    llm_api_key = None
    llm_host_url = None

    llm_provider = typer.prompt("What LLM provider would you like to use? (anthropic, openai, ollama)", default="anthropic", show_default=True)
    llm_model = typer.prompt("What model would you like to use? e.g. claude-sonnet-4-6, gpt-5.3-instant, or your own for ollama")

    if llm_provider == "ollama":
        llm_host_url = typer.prompt("Enter your LLM host URL")
    else:
        llm_api_key = typer.prompt("Enter your API Key.  It must correspond to the provider you selected.", hide_input=True)

    setup_config(llm_provider, llm_model, llm_api_key, llm_host_url)

@app.command()
def model():
    """
    Displays current model being used
    Allows user to change their model
    """
    typer.echo(f"Current model: {get_model()}")
    model_response =  typer.prompt("Enter new model to switch or press enter to keep current", default="", show_default=False)
    if model_response:
        update_model(model_response)
        typer.echo(f"Model updated to {model_response}")
    else:
        typer.echo("Model unchanged")

@app.command()
def provider():
    """
    Displays current provider being used
    Allows user to change their provider
    Allows user to change their model
    """
    typer.echo(f"Current provider: {get_provider()}")
    provider_response =  typer.prompt("Enter new provider to switch or press enter to keep current", default="", show_default=False)
    if provider_response:
        update_provider(provider_response)
        typer.echo(f"Provider updated to {provider_response}")

        if provider_response.lower() == "ollama":
            typer.echo("Since you switched to Ollama, you'll need to set your LLM host URL.")
            llm_host()

        model_response = typer.prompt("Would you like to update your model as well? (y/n)", default="y",
                                      show_default=True)
        if model_response.lower() == "y" or model_response.lower() == "yes":
            model()
    else:
        typer.echo("Provider unchanged")

@app.command()
def api_key():
    """
    Displays current API key being used
    Allows user to change their API key
    """
    typer.echo(f"Current API key: {get_api_key()}")
    key_response = typer.prompt("Enter new API key to switch or press enter to keep current", default="", show_default=False, hide_input=True)
    if key_response:
        update_api_key(key_response)
        typer.echo("API key updated")
    else:
        typer.echo("API key unchanged")

@app.command()
def llm_host():
    """
    Displays current Ollama host URL
    Allows user to change their Ollama host URL
    """
    current = get_llm_host()
    if current is None:
        typer.echo("No Ollama host set")
    else:
        typer.echo(f"Current Ollama host: {current}")
    host_response = typer.prompt("Enter new Ollama host URL or press enter to keep current", default="", show_default=False)
    if host_response:
        update_llm_host(host_response)
        typer.echo(f"Ollama host updated to {host_response}")
    else:
        typer.echo("Ollama host unchanged")