"""Wrapper to run the DPE pipeline from a seed idea and return the PRD text.

This is a convenience module for programmatic callers (like the dashboard
API) that need a simple function to go from idea → PRD content string.

Usage:
    from dpe.seed_to_prd import seed_to_prd
    prd_text = seed_to_prd("A task management app with AI prioritization")
"""

from __future__ import annotations

import logging
from pathlib import Path

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

logger = logging.getLogger(__name__)


def seed_to_prd(
    idea: str,
    output_dir: str = "runs",
    config_path: str | None = None,
    simulation: bool = False,
) -> str:
    """Run the DPE pipeline from a seed idea and return the PRD content.

    Args:
        idea: The seed idea/description to generate a PRD from.
        output_dir: Directory for DPE run artifacts.
        config_path: Optional path to DPE config file.
        simulation: If True, run in simulation mode (no real LLM calls).

    Returns:
        The generated PRD content as a string.

    Raises:
        RuntimeError: If PRD generation fails.
    """
    from dpe.adapters.registry import build_adapters

    overrides: dict[str, object] = {"output_dir": output_dir}
    if simulation:
        overrides["simulation_mode"] = True

    cfg = load_config(config_path, **overrides)
    adapters = build_adapters(cfg)
    orchestrator = Orchestrator(config=cfg, adapters=adapters)

    manifest = orchestrator.run(idea)

    if manifest.stop_reason != "completed":
        raise RuntimeError(
            f"DPE run did not complete (stop_reason={manifest.stop_reason}). "
            f"Warnings: {manifest.warnings}"
        )

    # Find the PRD artifact
    prd_content = ""
    for artifact in manifest.artifacts:
        path = Path(artifact) if isinstance(artifact, str) else artifact
        if hasattr(path, "name") and "prd" in str(path).lower():
            prd_content = Path(path).read_text(encoding="utf-8")
            break

    if not prd_content:
        # Fallback: read the latest .md file from the run directory
        run_dir = Path(orchestrator._registry.run_dir)
        md_files = sorted(run_dir.glob("*.md"), key=lambda p: p.stat().st_mtime, reverse=True)
        if md_files:
            prd_content = md_files[0].read_text(encoding="utf-8")

    if not prd_content:
        raise RuntimeError("DPE run completed but no PRD artifact was found.")

    logger.info("Generated PRD: %d chars from run %s", len(prd_content), manifest.run_id)
    return prd_content
