"""MCP tool: dialectic.generate_prd

Exposes the DPE orchestrator as an MCP tool for integration with
the Multi Agent Orchestrator (MCO).
"""

from __future__ import annotations

import logging
from typing import Any

from pydantic import ValidationError

from dpe.engine.config_loader import load_config
from dpe.engine.orchestrator import Orchestrator

logger = logging.getLogger(__name__)


def generate_prd(
    idea: str,
    context: dict[str, Any] | None = None,
    config_overrides: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """MCP tool implementation: dialectic.generate_prd

    Always returns a structured dict. On validation errors, returns
    an error response without starting a run. On runtime errors,
    returns a partial manifest with stop_reason set.
    """
    overrides = config_overrides or {}

    # Validate config before starting run
    try:
        config = load_config(**overrides)
    except (ValidationError, ValueError, FileNotFoundError) as e:
        logger.error("Config validation failed: %s", e)
        return {
            "final_prd_markdown": "",
            "run_id": "",
            "artifact_path": "",
            "run_manifest": {
                "stop_reason": "config_error",
                "error": str(e),
            },
            "warnings": [f"Config error: {e}"],
        }

    orchestrator = Orchestrator(config=config)
    manifest = orchestrator.run(idea)

    # Find the final PRD content
    final_prd = ""
    for artifact in reversed(manifest.artifacts):
        if (
            artifact.filename.startswith("80_prd")
            or artifact.filename == "60_prd_v2.md"
        ):
            path = orchestrator._registry.run_dir / artifact.filename
            if path.exists():
                final_prd = path.read_text(encoding="utf-8")
                break

    return {
        "final_prd_markdown": final_prd,
        "run_id": manifest.run_id,
        "artifact_path": str(orchestrator._registry.run_dir),
        "run_manifest": manifest.model_dump(mode="json"),
        "warnings": manifest.warnings,
    }


# MCP tool schema for registration
MCP_TOOL_SCHEMA: dict[str, Any] = {
    "name": "dialectic.generate_prd",
    "description": (
        "Generate a development-ready PRD from a base idea"
        " using a bounded dialectical workflow."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "idea": {
                "type": "string",
                "description": "The base idea to generate a PRD from.",
            },
            "context": {
                "type": "object",
                "description": "Optional context object.",
            },
            "config_overrides": {
                "type": "object",
                "description": "Optional config overrides.",
            },
        },
        "required": ["idea"],
    },
    "outputSchema": {
        "type": "object",
        "properties": {
            "final_prd_markdown": {"type": "string"},
            "run_id": {"type": "string"},
            "artifact_path": {"type": "string"},
            "run_manifest": {"type": "object"},
            "warnings": {
                "type": "array",
                "items": {"type": "string"},
            },
        },
        "required": [
            "final_prd_markdown",
            "run_id",
            "artifact_path",
            "run_manifest",
            "warnings",
        ],
    },
}
