"""Create method for collections namespace."""

from __future__ import annotations

from typing import Any

import msgspec

from pinecone._internal.logging import get_logger
from pinecone._internal.validation import require_non_empty
from pinecone.models.collections import CreateCollectionRequest


logger = get_logger(__name__)


def create(
    self: Any,
    name: str,
    *,
    source: str,
    timeout: int | None = None,
) -> None:
    """Create a collection from a pod-based index.

    This operation is asynchronous. The collection is created in the background
    and may take time to complete (typically ~10 minutes for p1/s1 pods,
    potentially several hours for p2 pods with millions of vectors).

    Use describe() to poll the collection status until it shows "Ready".

    Args:
        name: Collection name (1-45 chars, lowercase alphanumeric or '-').
        source: Source pod-based index name to create collection from.
        timeout: Optional timeout in seconds for the API request (not the
            collection creation itself).

    Raises:
        ValueError: If name or source is empty, or timeout is not positive.
        APIError: If creation fails.
        NotFoundError: If source index not found.

    Example:
        >>> pc.collections.create(name="my-backup", source="my-index")
        >>>
        >>> # Poll until ready
        >>> import time
        >>> while True:
        ...     info = pc.collections.describe("my-backup")
        ...     if info.status == "Ready":
        ...         break
        ...     time.sleep(10)
    """
    # Validate inputs
    require_non_empty("name", name)
    require_non_empty("source", source)
    if timeout is not None and timeout <= 0:
        raise ValueError("timeout must be a positive integer")

    logger.info(
        "Creating collection",
        collection_name=name,
        source_index=source,
        timeout=timeout,
    )

    try:
        # Build request
        request = CreateCollectionRequest(name=name, source=source)

        # Make HTTP request
        self._http.post(
            f"{self._base_url}/collections",
            content=msgspec.json.encode(request),
            headers={**self._headers, "Content-Type": "application/json"},
            timeout=timeout,
        )

        logger.info("Collection created successfully", collection_name=name)
        # Note: API returns 201 with CollectionModel, but we return None per protocol

    except Exception:
        logger.exception("Failed to create collection", collection_name=name, source_index=source)
        raise
