"""JSON formatter for machine-readable output.

Provides JSON output suitable for scripting and automation.
"""

import json
from typing import Any

from cli.infrastructure.formatters.base import ColumnMeta, Formatter


class JsonFormatter(Formatter):
    """Formatter that outputs JSON for scripting and automation."""

    def __init__(self, indent: int = 2):
        """Initialize JSON formatter.

        Args:
            indent: Number of spaces for JSON indentation
        """
        self.indent = indent

    def format_entity(self, data: dict[str, Any], title: str | None = None) -> str:
        """Format entity as JSON object.

        Args:
            data: Dictionary mapping field labels to values
            title: Ignored for JSON output

        Returns:
            JSON string
        """
        return json.dumps(data, indent=self.indent, default=str)

    def format_list(
        self,
        items: list[dict[str, Any]],
        title: str | None = None,
        columns: list[ColumnMeta] | None = None,
    ) -> str:
        """Format list as JSON array.

        Args:
            items: List of dictionaries
            title: Ignored for JSON output
            columns: Ignored for JSON output

        Returns:
            JSON string
        """
        return json.dumps(items, indent=self.indent, default=str)

    def format_success(self, message: str) -> str:
        """Format success message as JSON.

        Args:
            message: Success message text

        Returns:
            JSON string with status and message
        """
        return json.dumps({"status": "success", "message": message}, indent=self.indent)

    def format_info(self, message: str) -> str:
        """Format info message as JSON.

        Args:
            message: Info message text

        Returns:
            JSON string with status and message
        """
        return json.dumps({"status": "info", "message": message}, indent=self.indent)

    def format_warning(self, message: str) -> str:
        """Format warning message as JSON.

        Args:
            message: Warning message text

        Returns:
            JSON string with status and message
        """
        return json.dumps({"status": "warning", "message": message}, indent=self.indent)

    def format_result(
        self,
        action: str,
        resource: str,
        status: str = "success",
        identifier: str | None = None,
        name: str | None = None,
        extra_fields: dict[str, Any] | None = None,
    ) -> str:
        result: dict[str, Any] = {
            "action": action,
            "resource": resource,
            "status": status,
        }
        if identifier is not None:
            result["id"] = identifier
        if name is not None:
            result["name"] = name
        if extra_fields:
            result.update(extra_fields)
        return json.dumps(result, indent=self.indent)
