"""Metadata generation for auto-generated files.

Provides helpers to add metadata blocks to baseline files indicating they
are auto-generated by doc-manager-mcp.
"""

from importlib.metadata import version

# Tool version - fetched from package metadata
try:
    TOOL_VERSION = version("doc-manager-mcp")
except Exception:
    TOOL_VERSION = "unknown"

# Standard warning message
AUTO_GENERATED_WARNING = (
    "AUTO-GENERATED FILE - Do not edit manually. "
    "Changes will be overwritten by doc-manager."
)


def get_json_meta() -> dict:
    """Get metadata block for JSON baseline files.

    Returns a dict to be included as "_meta" at the top of JSON files.

    Returns:
        dict with generated_by, tool_version, and warning fields
    """
    return {
        "generated_by": "doc-manager-mcp",
        "tool_version": TOOL_VERSION,
        "warning": AUTO_GENERATED_WARNING,
    }


def get_yaml_header() -> str:
    """Get header comment for YAML files.

    Returns a multi-line comment string to prepend to YAML files.

    Returns:
        String with YAML comment header
    """
    return f"""# =============================================================================
# AUTO-GENERATED FILE - Do not edit manually
# Generated by: doc-manager-mcp v{TOOL_VERSION}
# Changes will be overwritten when baselines are updated.
# =============================================================================

"""


def insert_meta_first(data: dict) -> dict:
    """Insert _meta as the first key in a dict (for JSON serialization order).

    Python 3.7+ dicts maintain insertion order, so we reconstruct the dict
    with _meta first.

    Args:
        data: Original dict without _meta

    Returns:
        New dict with _meta as first key, followed by original keys
    """
    meta = get_json_meta()
    return {"_meta": meta, **data}
