"""OpenAPI spec generation for Albus HTTP transport.

We keep this intentionally lightweight (no third-party OpenAPI generator) so it
can't drift away from the actual code and is easy to edit.
"""

from __future__ import annotations

from typing import Any


def _get_common_schemas() -> dict[str, Any]:
    """Get common reusable schemas."""
    return {
        "SuccessResponse": {
            "type": "object",
            "properties": {
                "success": {"type": "boolean", "default": True},
                "request_id": {"type": "string", "description": "Request ID for correlation"},
                "timestamp": {
                    "type": "string",
                    "format": "date-time",
                    "description": "Response timestamp",
                },
            },
            "required": ["success"],
        },
        "ErrorResponse": {
            "type": "object",
            "properties": {
                "success": {"type": "boolean", "default": False},
                "error": {"type": "string", "description": "Human-readable error message"},
                "code": {"type": "string", "description": "Error code"},
                "request_id": {"type": "string", "description": "Request ID for correlation"},
                "details": {
                    "oneOf": [
                        {"type": "object"},
                        {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "field": {"type": "string"},
                                    "message": {"type": "string"},
                                    "code": {"type": "string"},
                                },
                            },
                        },
                    ],
                },
                "timestamp": {"type": "string", "format": "date-time"},
            },
            "required": ["success", "error", "code"],
        },
        "AgentDefinition": {
            "type": "object",
            "properties": {
                "id": {"type": "string"},
                "name": {"type": "string"},
                "instructions": {"type": "string"},
                "tools": {"type": "array", "items": {"type": "string"}},
                "skills": {"type": "array", "items": {"type": "string"}},
                "model": {"type": "string"},
                "max_steps": {"type": "integer"},
                "temperature": {"type": "number"},
                "pathway": {
                    "type": "string",
                    "description": "Pathway ID for agent execution",
                },
            },
        },
        # ----- Run schemas -----
        "RunSummary": {
            "type": "object",
            "properties": {
                "run_id": {"type": "string"},
                "status": {"type": "string", "enum": ["running", "completed", "failed"]},
                "started_at_ms": {"type": "integer", "nullable": True},
                "finished_at_ms": {"type": "integer", "nullable": True},
                "duration_ms": {"type": "integer", "nullable": True},
                "error": {"type": "string", "nullable": True},
                "workspace_id": {"type": "string", "nullable": True},
                "doc_id": {"type": "string", "nullable": True},
            },
            "required": ["run_id", "status"],
        },
        "RunListResponse": {
            "allOf": [
                {"$ref": "#/components/schemas/SuccessResponse"},
                {
                    "type": "object",
                    "properties": {
                        "runs": {
                            "type": "array",
                            "items": {"$ref": "#/components/schemas/RunSummary"},
                        },
                        "count": {"type": "integer"},
                    },
                    "required": ["runs", "count"],
                },
            ],
        },
        "RunDetailResponse": {
            "allOf": [
                {"$ref": "#/components/schemas/SuccessResponse"},
                {
                    "type": "object",
                    "properties": {
                        "run_id": {"type": "string"},
                        "pathway_id": {"type": "string", "nullable": True},
                        "pathway_name": {"type": "string", "nullable": True},
                        "status": {"type": "string"},
                        "started_at_ms": {"type": "integer", "nullable": True},
                        "finished_at_ms": {"type": "integer", "nullable": True},
                        "duration_ms": {"type": "integer", "nullable": True},
                        "inputs": {"type": "object", "nullable": True},
                        "outputs": {"type": "object", "nullable": True},
                        "error": {"type": "string", "nullable": True},
                        "workspace_id": {"type": "string", "nullable": True},
                        "doc_id": {"type": "string", "nullable": True},
                        "node_count": {"type": "integer"},
                        "event_count": {"type": "integer"},
                    },
                    "required": ["run_id", "status"],
                },
            ],
        },
        "RunSpanItem": {
            "type": "object",
            "properties": {
                "span_id": {"type": "string", "nullable": True},
                "parent_span_id": {"type": "string", "nullable": True},
                "kind": {"type": "string", "nullable": True},
                "name": {"type": "string", "nullable": True},
                "start_ms": {"type": "integer", "nullable": True},
                "end_ms": {"type": "integer", "nullable": True},
                "duration_ms": {"type": "integer", "nullable": True},
                "status": {"type": "string", "nullable": True},
                "error": {"type": "string", "nullable": True},
                "attributes": {"type": "object"},
                "inputs": {"type": "object", "nullable": True},
                "outputs": {"type": "object", "nullable": True},
            },
        },
        "RunSpansResponse": {
            "allOf": [
                {"$ref": "#/components/schemas/SuccessResponse"},
                {
                    "type": "object",
                    "properties": {
                        "run_id": {"type": "string"},
                        "spans": {
                            "type": "array",
                            "items": {"$ref": "#/components/schemas/RunSpanItem"},
                        },
                        "count": {"type": "integer"},
                    },
                    "required": ["run_id", "spans", "count"],
                },
            ],
        },
        "RunEventItem": {
            "type": "object",
            "properties": {
                "seq": {"type": "integer"},
                "ts_ms": {"type": "integer"},
                "type": {"type": "string"},
                "node_id": {"type": "string", "nullable": True},
                "payload": {"type": "object"},
            },
            "required": ["seq", "ts_ms", "type"],
        },
        "RunEventsResponse": {
            "allOf": [
                {"$ref": "#/components/schemas/SuccessResponse"},
                {
                    "type": "object",
                    "properties": {
                        "run_id": {"type": "string"},
                        "events": {
                            "type": "array",
                            "items": {"$ref": "#/components/schemas/RunEventItem"},
                        },
                        "count": {"type": "integer"},
                        "has_more": {"type": "boolean"},
                    },
                    "required": ["run_id", "events", "count"],
                },
            ],
        },
        # ----- Infrastructure schemas -----
        "HealthResponse": {
            "type": "object",
            "properties": {
                "status": {"type": "string", "enum": ["ok"]},
                "uptime_seconds": {"type": "number", "nullable": True},
            },
            "required": ["status"],
        },
        "ReadyResponse": {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["ready", "not_ready", "ok", "degraded", "down"],
                },
                "checks": {
                    "type": "object",
                    "additionalProperties": {"type": "string"},
                    "description": "Dependency check results",
                },
                "request_id": {"type": "string", "nullable": True},
            },
            "required": ["status"],
        },
        "ConfigValidateResponse": {
            "type": "object",
            "properties": {
                "valid": {"type": "boolean"},
                "errors": {"type": "array", "items": {"type": "string"}},
                "deployment": {"type": "object"},
                "warnings": {"type": "array", "items": {"type": "string"}},
                "config": {"type": "object"},
                "request_id": {"type": "string", "nullable": True},
            },
            "required": ["valid"],
        },
        # ----- Webhook schemas -----
        "WebhookResponse": {
            "allOf": [
                {"$ref": "#/components/schemas/SuccessResponse"},
                {
                    "type": "object",
                    "properties": {
                        "topic": {"type": "string"},
                        "delivered": {"type": "integer"},
                    },
                    "required": ["topic", "delivered"],
                },
            ],
        },
    }


def build_openapi_spec(*, base_url: str = "/api/v1") -> dict[str, Any]:
    """Build complete OpenAPI 3.0 specification."""
    schemas = _get_common_schemas()

    return {
        "openapi": "3.0.3",
        "info": {
            "title": "AlbusOS API",
            "version": "1.0",
            "description": "AlbusOS HTTP + WebSocket API (v1). Build pathways, wire tools, run agents.",
            "contact": {"name": "AlbusOS Support", "url": "https://github.com/albusstudio/albusOS"},
        },
        "servers": [{"url": base_url, "description": "AlbusOS API Server"}],
        "tags": [
            {"name": "agents", "description": "Agent management and execution"},
            {"name": "pathways", "description": "Pathway CRUD and execution"},
            {"name": "tools", "description": "Tool registry and execution"},
            {"name": "skills", "description": "Skill discovery"},
            {"name": "infrastructure", "description": "Health, config, metadata"},
            {"name": "realtime", "description": "WebSocket and webhooks"},
            {"name": "docs", "description": "API documentation"},
            {"name": "runs", "description": "Run inspection and debugging"},
        ],
        "paths": {
            # =================================================================
            # DOCUMENTATION ENDPOINTS
            # =================================================================
            "/": {
                "get": {
                    "tags": ["docs"],
                    "summary": "API discovery",
                    "description": "Returns an endpoint map and basic server metadata.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }
                    },
                }
            },
            "/help": {
                "get": {
                    "tags": ["docs"],
                    "summary": "API help",
                    "description": "Comprehensive API documentation with examples.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }
                    },
                }
            },
            "/openapi.json": {
                "get": {
                    "tags": ["docs"],
                    "summary": "OpenAPI specification (v1)",
                    "description": "This OpenAPI 3.0 specification document.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }
                    },
                }
            },
            "/docs": {
                "get": {
                    "tags": ["docs"],
                    "summary": "Interactive API documentation (Swagger UI)",
                    "description": "Interactive API explorer powered by Swagger UI.",
                    "responses": {"200": {"description": "HTML", "content": {"text/html": {}}}},
                }
            },
            # =================================================================
            # INFRASTRUCTURE ENDPOINTS
            # =================================================================
            "/healthz": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "Liveness probe",
                    "description": "Returns 200 if the process is alive. No dependency checks.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {"$ref": "#/components/schemas/HealthResponse"},
                                }
                            },
                        }
                    },
                }
            },
            "/readyz": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "Readiness probe",
                    "description": "Returns 200 when the server can serve requests (runtime, pathway VM, LLM configured).",
                    "responses": {
                        "200": {
                            "description": "Ready",
                            "content": {
                                "application/json": {
                                    "schema": {"$ref": "#/components/schemas/ReadyResponse"},
                                }
                            },
                        },
                        "503": {
                            "description": "Not ready",
                            "content": {
                                "application/json": {
                                    "schema": {"$ref": "#/components/schemas/ReadyResponse"},
                                }
                            },
                        },
                    },
                }
            },
            "/health": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "Health check",
                    "description": "Health check with dependency status (runtime, pathway_vm, LLM, persistence).",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {"$ref": "#/components/schemas/ReadyResponse"},
                                }
                            },
                        }
                    },
                }
            },
            "/config/validate": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "Validate configuration",
                    "description": "Validate environment and deployment configuration.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/ConfigValidateResponse",
                                    },
                                }
                            },
                        }
                    },
                }
            },
            "/config/models": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "Get model routing configuration",
                    "description": "Get current model routing configuration.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }
                    },
                },
                "patch": {
                    "tags": ["infrastructure"],
                    "summary": "Update model routing configuration",
                    "description": "Update model routing configuration at runtime.",
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "default_profile": {"type": "string"},
                                        "routing": {"type": "object"},
                                    },
                                }
                            }
                        },
                    },
                    "responses": {"200": {"description": "OK"}},
                },
            },
            "/node-types": {
                "get": {
                    "tags": ["infrastructure"],
                    "summary": "List pathway node types",
                    "description": "List all available node types for pathway creation.",
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "node_types": {
                                                "type": "array",
                                                "items": {"type": "string"},
                                            },
                                        },
                                    }
                                }
                            },
                        }
                    },
                }
            },
            # =================================================================
            # AGENTS - The core primitive
            # =================================================================
            "/agents": {
                "get": {
                    "tags": ["agents"],
                    "summary": "List registered agents",
                    "description": "List all registered agents with optional instructions preview.",
                    "parameters": [
                        {
                            "name": "instructions",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string", "enum": ["preview", "full", "none"], "default": "preview"},
                            "description": "Instructions display mode",
                        },
                        {
                            "name": "preview_limit",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "integer", "default": 200},
                            "description": "Character limit for instructions preview",
                        },
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "agents": {
                                                        "type": "array",
                                                        "items": {"type": "object"},
                                                    },
                                                    "count": {"type": "integer"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        }
                    },
                },
            },
            "/agents/{agent_id}": {
                "get": {
                    "tags": ["agents"],
                    "summary": "Get agent details",
                    "description": "Get detailed information about a specific agent.",
                    "parameters": [
                        {
                            "name": "agent_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                            "description": "Agent identifier",
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object"}}}},
                        "404": {"description": "Agent not found", "$ref": "#/components/responses/Error"},
                    },
                },
            },
            "/agents/{agent_id}/turn": {
                "post": {
                    "tags": ["agents"],
                    "summary": "Execute an agent turn (main entry point)",
                    "description": "Send a message to an agent and receive a response. Use agent_id='host' for the primary assistant.",
                    "parameters": [
                        {
                            "name": "agent_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "message": {"type": "string", "minLength": 1, "maxLength": 100000},
                                        "thread_id": {"type": "string", "description": "Thread ID for conversation context"},
                                        "context": {"type": "object", "description": "Additional context"},
                                        "attachments": {
                                            "type": "array",
                                            "items": {"type": "object"},
                                            "description": "File attachments (images, documents)",
                                        },
                                        "pathway": {
                                            "type": "string",
                                            "description": "Override agent's default pathway",
                                        },
                                    },
                                    "required": ["message"],
                                }
                            }
                        },
                    },
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "response": {"type": "string"},
                                                    "completed": {"type": "boolean"},
                                                    "steps_taken": {"type": "integer"},
                                                    "agent_id": {"type": "string"},
                                                    "thread_id": {"type": "string"},
                                                    "pathway": {"type": "string"},
                                                    "error": {"type": "string"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        },
                        "404": {"description": "Agent not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/agents/{agent_id}/skills": {
                "get": {
                    "tags": ["agents"],
                    "summary": "List skills available to an agent",
                    "description": "List all skills that are available to a specific agent based on tool patterns.",
                    "parameters": [
                        {
                            "name": "agent_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "skills": {
                                                        "type": "array",
                                                        "items": {"type": "object"},
                                                    },
                                                    "count": {"type": "integer"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        },
                        "404": {"description": "Agent not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            # =================================================================
            # PATHWAYS
            # =================================================================
            "/pathways": {
                "get": {
                    "tags": ["pathways"],
                    "summary": "List pathways",
                    "description": "List all loaded pathways, optionally filtered by source.",
                    "parameters": [
                        {
                            "name": "source",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by source (e.g., 'config')",
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "pathways": {"type": "array", "items": {"type": "object"}},
                                                    "count": {"type": "integer"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        }
                    },
                },
            },
            "/pathways/{pathway_id}": {
                "get": {
                    "tags": ["pathways"],
                    "summary": "Get pathway",
                    "description": "Get detailed information about a pathway.",
                    "parameters": [
                        {
                            "name": "pathway_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Pathway not found", "$ref": "#/components/responses/Error"},
                    },
                },
            },
            "/pathways/{pathway_id}/run": {
                "post": {
                    "tags": ["pathways"],
                    "summary": "Run a pathway",
                    "description": "Execute a pathway with provided inputs.",
                    "parameters": [
                        {
                            "name": "pathway_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "requestBody": {
                        "required": False,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "inputs": {
                                            "type": "object",
                                            "description": "Input values for pathway execution",
                                        },
                                    },
                                }
                            }
                        },
                    },
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "outputs": {"type": "object"},
                                                    "execution_id": {"type": "string"},
                                                    "status": {"type": "string"},
                                                    "duration_ms": {"type": "number"},
                                                    "error": {"type": "string"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        },
                        "404": {"description": "Pathway not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/pathways/{pathway_id}/export": {
                "get": {
                    "tags": ["pathways"],
                    "summary": "Export a pathway",
                    "description": "Export pathway as JSON in server.pathway.v1 format.",
                    "parameters": [
                        {
                            "name": "pathway_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Pathway not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/pathways/{pathway_id}/graph": {
                "get": {
                    "tags": ["pathways"],
                    "summary": "Get pathway graph payload",
                    "description": "Get compact graph representation for visualization.",
                    "parameters": [
                        {
                            "name": "pathway_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Pathway not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            # =================================================================
            # SKILLS
            # =================================================================
            "/skills": {
                "get": {
                    "tags": ["skills"],
                    "summary": "List all registered skills",
                    "description": "List all available skills with optional filtering.",
                    "parameters": [
                        {
                            "name": "builtin",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "boolean"},
                            "description": "Filter to only builtin skills",
                        },
                        {
                            "name": "tag",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by tag",
                        },
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "skills": {"type": "array", "items": {"type": "object"}},
                                                    "count": {"type": "integer"},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        }
                    },
                }
            },
            "/skills/{skill_id}": {
                "get": {
                    "tags": ["skills"],
                    "summary": "Get skill details",
                    "description": "Get detailed skill information including full instructions.",
                    "parameters": [
                        {
                            "name": "skill_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Skill not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            # =================================================================
            # TOOLS
            # =================================================================
            "/tools": {
                "get": {
                    "tags": ["tools"],
                    "summary": "List registered tools",
                    "description": "List all available tools with optional filtering and grouping.",
                    "parameters": [
                        {
                            "name": "category",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by category (e.g., 'web', 'code', 'workspace')",
                        },
                        {
                            "name": "format",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string", "enum": ["list", "grouped"], "default": "list"},
                            "description": "Output format",
                        },
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "allOf": [
                                            {"$ref": "#/components/schemas/SuccessResponse"},
                                            {
                                                "type": "object",
                                                "properties": {
                                                    "tools": {"type": "array", "items": {"type": "object"}},
                                                    "count": {"type": "integer"},
                                                    "categories": {"type": "array", "items": {"type": "string"}},
                                                },
                                            },
                                        ]
                                    }
                                }
                            },
                        }
                    },
                }
            },
            "/tools/{tool_name}": {
                "post": {
                    "tags": ["tools"],
                    "summary": "Call a tool",
                    "description": "Execute a tool directly with provided arguments.",
                    "parameters": [
                        {
                            "name": "tool_name",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                            "description": "Tool name (e.g., 'web.search', 'code.execute')",
                        }
                    ],
                    "requestBody": {
                        "required": False,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "arguments": {"type": "object", "description": "Tool arguments"},
                                        "workspace_id": {"type": "string"},
                                        "thread_id": {"type": "string"},
                                    },
                                }
                            }
                        },
                    },
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Tool not found", "$ref": "#/components/responses/Error"},
                        "500": {"description": "Tool execution failed", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            # =================================================================
            # REALTIME
            # =================================================================
            "/ws": {
                "get": {
                    "tags": ["realtime"],
                    "summary": "WebSocket endpoint for streaming and events",
                    "description": "Connect via WebSocket for real-time pathway events and streaming responses.",
                    "responses": {"101": {"description": "Switching Protocols"}},
                }
            },
            "/webhooks/{topic}": {
                "post": {
                    "tags": ["realtime"],
                    "summary": "Publish webhook event (in-memory bus)",
                    "description": "Publish an event to the in-memory message bus.",
                    "parameters": [
                        {
                            "name": "topic",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                            "description": "Event topic",
                        }
                    ],
                    "requestBody": {
                        "required": False,
                        "content": {"application/json": {"schema": {"type": "object"}}},
                    },
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/WebhookResponse",
                                    },
                                }
                            },
                        }
                    },
                }
            },
            # =================================================================
            # RUN INSPECTION
            # =================================================================
            "/runs": {
                "get": {
                    "tags": ["runs"],
                    "summary": "List runs",
                    "description": "List execution runs for debugging and inspection.",
                    "parameters": [
                        {
                            "name": "limit",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "integer", "default": 50},
                            "description": "Maximum number of runs to return",
                        },
                        {
                            "name": "workspace_id",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by workspace",
                        },
                        {
                            "name": "doc_id",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by document (pathway)",
                        },
                        {
                            "name": "status",
                            "in": "query",
                            "required": False,
                            "schema": {
                                "type": "string",
                                "enum": ["running", "completed", "failed"],
                            },
                            "description": "Filter by status",
                        },
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/RunListResponse",
                                    },
                                }
                            },
                        }
                    },
                }
            },
            "/runs/{run_id}": {
                "get": {
                    "tags": ["runs"],
                    "summary": "Get run details",
                    "description": "Get detailed information about a specific run including inputs/outputs.",
                    "parameters": [
                        {
                            "name": "run_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/RunDetailResponse",
                                    },
                                }
                            },
                        },
                        "404": {"description": "Run not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/runs/{run_id}/spans": {
                "get": {
                    "tags": ["runs"],
                    "summary": "Get run spans",
                    "description": "Get hierarchical span tree for a run. Returns a flat list with parent_span_id for client-side tree reconstruction.",
                    "parameters": [
                        {
                            "name": "run_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/RunSpansResponse",
                                    },
                                }
                            },
                        },
                        "404": {"description": "Run not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/runs/{run_id}/events": {
                "get": {
                    "tags": ["runs"],
                    "summary": "Get run events",
                    "description": "Get event stream for a run. Supports polling via after_seq parameter.",
                    "parameters": [
                        {
                            "name": "run_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        },
                        {
                            "name": "after_seq",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "integer"},
                            "description": "Return events after this sequence number (for polling)",
                        },
                        {
                            "name": "limit",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "integer", "default": 500},
                            "description": "Max events to return",
                        },
                        {
                            "name": "type",
                            "in": "query",
                            "required": False,
                            "schema": {"type": "string"},
                            "description": "Filter by event type",
                        },
                    ],
                    "responses": {
                        "200": {
                            "description": "OK",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/RunEventsResponse",
                                    },
                                }
                            },
                        },
                        "404": {"description": "Run not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
            "/runs/{run_id}/timeline": {
                "get": {
                    "tags": ["runs"],
                    "summary": "Get run timeline",
                    "description": "Get chronological timeline of run execution.",
                    "parameters": [
                        {
                            "name": "run_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"},
                        }
                    ],
                    "responses": {
                        "200": {"description": "OK"},
                        "404": {"description": "Run not found", "$ref": "#/components/responses/Error"},
                    },
                }
            },
        },
        "components": {
            "schemas": schemas,
            "responses": {
                "Error": {
                    "description": "Error response",
                    "content": {
                        "application/json": {
                            "schema": {"$ref": "#/components/schemas/ErrorResponse"},
                        }
                    },
                },
            },
        },
    }
