"""Templates for opencrane init command."""

CONFIG_PY = '''\
from opencrane import OpenCraneConfig
# Uncomment to add custom fence type handlers:
# from opencrane.fences import CodeFenceConfig


class Config(OpenCraneConfig):
    """Project-specific OpenCrane configuration.

    Subclass OpenCraneConfig to register custom fence types,
    chunking strategies, and YAML tree walkers.
    See OpenCraneConfig for all available extension points.
    """

    # Register custom fence types for code blocks in your documentation.
    # The handler receives the fence content and returns a string to embed.
    # fence_types = {
    #     "openapi": CodeFenceConfig(fence_type="openapi", handler=my_openapi_handler),
    #     "json-schema": CodeFenceConfig(fence_type="json-schema", handler=my_schema_handler),
    # }

    # Prepend custom chunking strategies (first match wins).
    # chunking_strategies = [MyTabsStrategy(), *OpenCraneConfig.chunking_strategies]

    # Extend or replace YAML tree walkers for structured YAML chunking.
    # yaml_tree_walkers = [*OpenCraneConfig.yaml_tree_walkers, MyCustomWalker]
'''

SOURCES_YAML = '''\
# OpenCrane source mapping
# Defines repositories and local directories to include in the knowledge base.
#
# Each entry maps an output path (used as the local directory name) to its source.
#
# Remote GitHub repository example:
# external-sources/my-repo:
#   github_url: https://github.com/my-org/my-repo
#   docs_path: docs        # subdirectory inside the repo to fetch (empty = root)
#   manual: true           # true = always fetch, false = only if repo has the configured topic
#
# Local directory example (path relative to project root):
# local-docs/my-content:
#   github_url: ""
#   docs_path: my-local-content
#   manual: true

sources:
'''

DOCKERFILE = '''\
# syntax=docker/dockerfile:1.4
# Multi-stage build for OpenCrane MCP Server with embedded Milvus Lite
# Optimized for fast rebuilds when only Python code or data changes
# Generated by: opencrane init

# =============================================================================
# Stage 1: Dependencies (cached unless opencrane version changes)
# =============================================================================
FROM python:3.11-slim AS deps

WORKDIR /build

RUN apt-get update && apt-get install -y --no-install-recommends \\
    gcc \\
    g++ \\
    && rm -rf /var/lib/apt/lists/*

RUN --mount=type=cache,target=/root/.cache/pip \\
    pip install opencrane

# =============================================================================
# Stage 2: Model download (cached unless EMBEDDING_MODEL changes)
# =============================================================================
FROM deps AS model

ARG EMBEDDING_MODEL=nomic-ai/nomic-embed-text-v1.5
ENV EMBEDDING_MODEL=${EMBEDDING_MODEL}

RUN --mount=type=cache,target=/root/.cache/huggingface \\
    echo "Downloading embedding model..." && \\
    python3 -c "from sentence_transformers import SentenceTransformer; SentenceTransformer(\'${EMBEDDING_MODEL}\', trust_remote_code=True)" && \\
    mkdir -p /build/hf_cache && cp -r /root/.cache/huggingface /build/hf_cache/

# =============================================================================
# Stage 3: Milvus init (bake vector database into image at build time)
# =============================================================================
FROM deps AS milvus

WORKDIR /build

COPY .opencrane/ ./.opencrane/

ENV MILVUS_DB_PATH=/build/milvus_data/milvus.db
ENV COLLECTION_NAME=opencrane_chunks
ENV DROP_EXISTING=true
ENV PYTHONPATH=/build

RUN mkdir -p /build/milvus_data && opencrane index

# =============================================================================
# Stage 4: Final runtime image
# =============================================================================
FROM python:3.11-slim

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \\
    curl \\
    && rm -rf /var/lib/apt/lists/*

COPY --from=deps /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=deps /usr/local/bin /usr/local/bin

COPY --from=model /build/hf_cache/huggingface /root/.cache/huggingface

COPY --from=milvus /build/milvus_data /app/milvus_data

COPY .opencrane/ /app/.opencrane/

ENV MILVUS_DB_PATH=/app/milvus_data/milvus.db
ENV COLLECTION_NAME=opencrane_chunks
ENV MCP_HTTP_PORT=8000
ENV PYTHONUNBUFFERED=1
ENV TRANSFORMERS_OFFLINE=1

EXPOSE 8000

ENTRYPOINT ["opencrane", "serve", "--transport", "http"]
'''

DOCKER_COMPOSE = '''\
# Generated by: opencrane init
services:
  opencrane-mcp:
    build:
      context: ..
      dockerfile: .opencrane/Dockerfile
      args:
        EMBEDDING_MODEL: "${EMBEDDING_MODEL:-nomic-ai/nomic-embed-text-v1.5}"
    ports:
      - "8000:8000"
    environment:
      MILVUS_DB_PATH: /app/milvus_data/milvus.db
      COLLECTION_NAME: opencrane_chunks
'''

README_MD = '''\
# .opencrane

This directory contains OpenCrane configuration and generated data files.

## Structure

| File | Description | Commit? |
|---|---|---|
| `config.py` | Custom fence types, chunking strategies, tree walkers | Yes |
| `sources.yaml` | Which repos/directories to fetch documentation from | Yes |
| `chunks.json` | Generated document chunks (`opencrane chunk`) | Your choice |
| `embeddings.json` | Generated vector embeddings (`opencrane embed`) | Your choice |

> Committing `chunks.json` and `embeddings.json` is required for Docker image builds via CI/CD.
> For local-only use, you can add them to `.gitignore`.

## Quick Start

```bash
# 1. Edit sources.yaml to point at your documentation
# 2. Fetch and process docs
opencrane fetch
opencrane llms
opencrane chunk
opencrane embed

# 3. Start MCP server locally (no Docker)
opencrane index
opencrane serve

# 4. Or launch MCP Inspector for interactive testing
opencrane inspect

# 5. Or build and run via {container_tool}
{container_tool}-compose up --build
```

## Adding to your MCP client

Run `opencrane serve` and follow the printed instructions.
'''


def readme(podman: bool = False) -> str:
    tool = "podman" if podman else "docker"
    return README_MD.replace("{container_tool}", tool)
