"""Interactive questionnaire for foremet init."""

from pathlib import Path

import typer

from foremet.config.schema import ADKConfig, AuthType

CONFIG_FILENAME = "adk.config.json"
ENV_EXAMPLE_FILENAME = ".env.example"


def run_init_prompts(cwd: Path) -> ADKConfig:
    """Prompt for each required/optional field and return ADKConfig."""
    use_url = typer.confirm(
        "Do you have a URL for the OpenAPI spec? (No = use local file path)",
        default=True,
    )
    openapi_url: str | None = None
    openapi_path: str | None = None
    if use_url:
        openapi_url = typer.prompt(
            "OpenAPI spec URL (YAML or JSON)",
            default="https://petstore3.swagger.io/api/v3/openapi.json",
        ).strip()
    else:
        openapi_path = typer.prompt(
            "Path to OpenAPI spec file",
            default="./openapi.yaml",
        ).strip()

    product_name = typer.prompt("Product name", default="My SaaS").strip()
    product_description = typer.prompt(
        "Product description (optional, one line)",
        default="",
    ).strip() or None
    base_url = typer.prompt(
        "API base URL (e.g. https://api.example.com/v1)",
        default="https://api.example.com/v1",
    ).strip()
    auth_choice = typer.prompt(
        "Auth type: api_key, bearer, oauth2",
        default="bearer",
    ).strip().lower()
    try:
        auth_type = AuthType(auth_choice)
    except ValueError:
        auth_type = AuthType.bearer
    auth_env_var = typer.prompt(
        "Env var name for API key/token",
        default="SAAS_API_KEY",
    ).strip()
    output_dir = typer.prompt(
        "Output directory for generated agent",
        default="./agent",
    ).strip()
    llm_provider = typer.prompt(
        "LLM provider: openai, anthropic, gemini, or ollama",
        default="openai",
    ).strip().lower()
    if llm_provider not in ("openai", "anthropic", "gemini", "ollama"):
        llm_provider = "openai"
    default_models = {"openai": "gpt-4o-mini", "anthropic": "claude-3-5-haiku-20241022", "gemini": "gemini-1.5-flash", "ollama": "llama3.2"}
    model = typer.prompt(
        "Model name",
        default=default_models.get(llm_provider, "gpt-4o-mini"),
    ).strip()

    return ADKConfig(
        openapi_url=openapi_url,
        openapi_path=openapi_path,
        product_name=product_name,
        product_description=product_description,
        base_url=base_url,
        auth_type=auth_type,
        auth_env_var=auth_env_var,
        output_dir=output_dir,
        llm_provider=llm_provider,
        model=model,
    )


def write_config(cwd: Path, config: ADKConfig) -> Path:
    """Write adk.config.json to cwd. Return path."""
    path = cwd / CONFIG_FILENAME
    path.write_text(config.model_dump_json(indent=2))
    return path


def write_env_example(cwd: Path, auth_env_var: str, llm_provider: str = "openai") -> Path:
    """Write .env.example with placeholders for auth and LLM keys."""
    path = cwd / ENV_EXAMPLE_FILENAME
    lines = [
        "# Copy to .env and fill in values.",
        f"# API key/token for the SaaS (read from {auth_env_var})",
        f"{auth_env_var}=your_saas_api_key_here",
        "",
        "# LLM (set the one for your chosen provider):",
        "OPENAI_API_KEY=your_openai_api_key_here",
        "ANTHROPIC_API_KEY=your_anthropic_api_key_here",
        "GOOGLE_API_KEY=your_google_api_key_here",
        "# Ollama (optional; default http://localhost:11434)",
        "OLLAMA_BASE_URL=http://localhost:11434",
    ]
    content = "\n".join(lines) + "\n"
    path.write_text(content)
    return path
