"""Generate tool manifest for AI agents.

`mcpbundles init` writes a point-in-time snapshot of available tools
to mcpbundles_tools.md or mcpbundles_tools.json. AI agents read this
to discover available tools without MCP. The manifest is explicitly
stamped as a snapshot that may become stale.
"""

import json
from datetime import datetime, timezone
from pathlib import Path


def generate_markdown_manifest(tools: list, output: Path, connection_name: str | None = None) -> None:
    lines: list[str] = [
        "# MCPBundles Available Tools",
        "",
        f"*Generated at {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}*",
        "",
        "> **Snapshot**: This file was generated by `mcpbundles init` and may become stale.",
        "> Run `mcpbundles init` again to refresh.",
        "",
    ]
    if connection_name:
        lines.append(f"Connection: `{connection_name}`")
        lines.append("")

    lines.append(f"## Tools ({len(tools)} total)")
    lines.append("")

    for tool in sorted(tools, key=lambda t: t.name):
        lines.append(f"### `{tool.name}`")
        lines.append("")
        if tool.description:
            lines.append(tool.description.strip())
            lines.append("")

        schema = tool.inputSchema or {}
        properties = schema.get("properties", {})
        required_fields = set(schema.get("required", []))

        if properties:
            lines.append("**Parameters:**")
            lines.append("")
            for prop_name, prop_schema in properties.items():
                is_req = prop_name in required_fields
                ptype = prop_schema.get("type", "any")
                desc = prop_schema.get("description", "")
                marker = "**required**" if is_req else "optional"
                enum_vals = prop_schema.get("enum")
                enum_str = f", one of: `{enum_vals}`" if enum_vals else ""
                lines.append(f"- `{prop_name}` ({ptype}, {marker}){enum_str}: {desc}")
            lines.append("")

    output.write_text("\n".join(lines))


def generate_json_manifest(tools: list, output: Path, connection_name: str | None = None) -> None:
    data = {
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "snapshot": True,
        "connection": connection_name,
        "tool_count": len(tools),
        "tools": [
            {
                "name": t.name,
                "description": t.description,
                "inputSchema": t.inputSchema,
            }
            for t in sorted(tools, key=lambda t: t.name)
        ],
    }
    output.write_text(json.dumps(data, indent=2))
