# fitz_ai/cli/commands/init_config.py
"""
Config generation for init wizard.

Pure functions that generate YAML configuration strings.
"""

from __future__ import annotations


def generate_global_config(default_engine: str) -> str:
    """Generate the global config YAML with just default_engine."""
    return f"""# Fitz Global Configuration
# Generated by: fitz init

# Default engine for CLI commands
default_engine: {default_engine}
"""


def generate_fitz_rag_config(
    *,
    chat: str,
    chat_model_smart: str,
    chat_model_fast: str,
    chat_model_balanced: str = "",
    embedding: str,
    embedding_model: str,
    rerank: str | None,
    rerank_model: str,
    vector_db: str,
    retrieval: str,
    chunker: str,
    chunk_size: int,
    chunk_overlap: int,
    parser: str = "docling",
    vision: str | None = None,
    vision_model: str = "",
) -> str:
    """Generate the Fitz RAG config YAML string."""
    # Build chat kwargs with smart/fast/balanced models
    chat_kwargs = ""
    if chat_model_smart or chat_model_fast or chat_model_balanced:
        chat_kwargs = "\n    models:"
        if chat_model_smart:
            chat_kwargs += f"\n      smart: {chat_model_smart}"
        if chat_model_fast:
            chat_kwargs += f"\n      fast: {chat_model_fast}"
        if chat_model_balanced:
            chat_kwargs += f"\n      balanced: {chat_model_balanced}"
        chat_kwargs += "\n    temperature: 0.2"

    # Build embedding kwargs
    embedding_kwargs = ""
    if embedding_model:
        embedding_kwargs = f"\n    model: {embedding_model}"

    # Build rerank section
    if rerank:
        rerank_kwargs = " {}"
        if rerank_model:
            rerank_kwargs = f"\n    model: {rerank_model}"
        rerank_section = f"""
# Reranker (improves retrieval quality - prompted at query time)
rerank:
  plugin_name: {rerank}
  kwargs:{rerank_kwargs}
"""
    else:
        rerank_section = """
# Reranker (no reranker available - install cohere or similar)
# rerank:
#   plugin_name: cohere
#   kwargs:
#     model: rerank-v3.5
"""

    # Build vector DB kwargs (pgvector uses mode: local by default)
    vdb_kwargs = ""
    if vector_db == "pgvector":
        vdb_kwargs = "\n    mode: local"

    # Build chunking section
    chunking_section = f"""
# Chunking (document splitting for ingestion)
# parser: docling (default) or docling_vision (VLM-powered figure description)
chunking:
  default:
    parser: {parser}
    plugin_name: {chunker}
    kwargs:
      chunk_size: {chunk_size}
      chunk_overlap: {chunk_overlap}
  by_extension: {{}}
"""

    # Build vision section
    if vision:
        vision_kwargs = " {}"
        if vision_model:
            vision_kwargs = f"\n    model: {vision_model}"
        vision_section = f"""
# Vision (VLM for describing figures/images in PDFs - prompted at ingest time)
vision:
  plugin_name: {vision}
  kwargs:{vision_kwargs}
"""
    else:
        vision_section = """
# Vision (VLM for describing figures/images in PDFs)
# Uncomment to enable - requires OPENAI_API_KEY, ANTHROPIC_API_KEY, or Ollama
# vision:
#   plugin_name: openai  # or anthropic, cohere, local_ollama
#   kwargs: {}
"""

    return f"""# Fitz RAG Engine Configuration
# Generated by: fitz init

# Chat (LLM for answering questions)
# smart: Best quality for user-facing responses (queries)
# fast: Best speed for background tasks (enrichment, summaries)
chat:
  plugin_name: {chat}
  kwargs:{chat_kwargs}

# Embedding (text to vectors)
embedding:
  plugin_name: {embedding}
  kwargs:{embedding_kwargs}
{rerank_section}
# Vector Database
vector_db:
  plugin_name: {vector_db}
  kwargs:{vdb_kwargs if vdb_kwargs else " {}"}

# Retrieval (YAML-based plugin)
retrieval:
  plugin_name: {retrieval}
  collection: default
  top_k: 5
{chunking_section}{vision_section}
# RGS (Retrieval-Guided Synthesis)
rgs:
  enable_citations: true
  strict_grounding: true
  max_chunks: 8

# Logging
logging:
  level: INFO
"""


def copy_engine_default_config(engine_name: str, registry) -> str | None:
    """
    Get the content of an engine's default config file.

    Uses the registry to discover the engine's default config path,
    then reads and returns its contents.

    Args:
        engine_name: Name of the engine
        registry: The engine registry instance

    Returns:
        Config file contents as string, or None if no default config
    """
    default_path = registry.get_default_config_path(engine_name)
    if default_path is None or not default_path.exists():
        return None

    return default_path.read_text(encoding="utf-8")
