"""Base Builder class for all output builders.

This module provides the Builder abstract base class that defines the interface
for all AI tool-specific output builders. Each builder transforms the prompt
registry into the specific format required by different AI assistant tools.

Classes:
    Builder: Abstract base class for output builders.

Example:
    >>> from promptosaurus.builders.builder import Builder
    >>> # Subclass to create a new builder
    >>> class MyToolBuilder(Builder):
    ...     def build(self, output, config=None, dry_run=False):
    ...         # Implementation
    ...         return ["Created config files"]
"""

from datetime import datetime
from pathlib import Path
from typing import Any

from promptosaurus.registry import registry


class Builder:
    """Base class for all builders that generate output configs.

    This abstract class defines the interface that all tool-specific builders
    must implement. Subclasses should override the build() method to generate
    the appropriate output format for their target AI tool.

    Attributes:
        _base_files: List of core prompt files included in all builds.

    Methods:
        build: Generate output configuration files.
        _build_concatenated: Create concatenated rules file content.
    """

    _base_files = [
        "agents/core/core-system.md",
        "agents/core/core-conventions.md",
        "agents/core/core-session.md",
    ]

    def build(
        self, output: Path, config: dict[str, Any] | None = None, dry_run: bool = False
    ) -> list[str]:
        """Build output configs.

        This method should be overridden by subclasses to generate tool-specific
        configuration files.

        Args:
            output: Directory to write output into.
            config: Optional configuration dict with template variables.
            dry_run: If True, preview what would be written without touching filesystem.

        Returns:
            List of action strings describing what was done.

        Raises:
            NotImplementedError: If subclass doesn't implement this method.
        """
        raise NotImplementedError("Subclasses must implement build()")

    @classmethod
    def _build_concatenated(cls, tool_comment: str) -> str:
        """Returns the full text of a concatenated rules file.

        This helper method creates a concatenated rules file by combining all
        prompts in the registry's concat_order, with section headers.

        Args:
            tool_comment: First-line comment identifying the tool (e.g., '# .clinerules').

        Returns:
            Complete concatenated rules file content as a string.

        Example:
            >>> content = cls._build_concatenated('# .clinerules')
            >>> print(content[:100])
            # .clinerules
            # Auto-generated by prompt CLI...
        """
        now = datetime.now().strftime("%Y-%m-%d %H:%M")
        lines: list[str] = [
            tool_comment,
            "# Auto-generated by prompt CLI — edit files in prompts/ then rebuild",
            f"# Last built: {now}",
            "",
        ]

        for label, filename in registry.concat_order:
            try:
                body = registry.prompt_body(filename)
            except FileNotFoundError:
                lines.append(f"## {label} — MISSING: {filename}")
                lines.append("")
                continue

            lines.append("---")
            lines.append(f"## {label}")
            lines.append("")
            lines.append(body.rstrip())
            lines.append("")

        return "\n".join(lines) + "\n"
