# Copyright 2025 Softwell S.r.l.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Output formatting for CLI responses."""

from __future__ import annotations

import json
from typing import Any

__all__ = ["OutputFormatter"]


class OutputFormatter:
    """Formats WSX response data for terminal display."""

    __slots__ = ()

    def format(self, data: Any, mode: str = "json") -> str:
        """Format data for display.

        Args:
            data: Response data to format.
            mode: Output mode — 'json', 'table', 'raw'.
        """
        if mode == "table":
            return self.format_table(data)
        if mode == "raw":
            return self.format_raw(data)
        return self.format_json(data)

    def format_json(self, data: Any) -> str:
        """Pretty-print as indented JSON."""
        if isinstance(data, str):
            return data
        return json.dumps(data, indent=2, ensure_ascii=False, default=str)

    def format_table(self, data: Any) -> str:
        """Format as a simple text table (for lists of dicts)."""
        if isinstance(data, list) and data and isinstance(data[0], dict):
            return self._dict_list_table(data)
        if isinstance(data, dict):
            return self._dict_table(data)
        return self.format_json(data)

    def format_raw(self, data: Any) -> str:
        """Minimal formatting — str() for non-strings."""
        if isinstance(data, str):
            return data
        return str(data)

    def format_response(self, response: dict[str, Any]) -> str:
        """Format a full WSX response with status."""
        status = response.get("status", "?")
        data = response.get("data")

        if status >= 400:
            return self.format_error(status, data)

        return self.format_json(data)

    def format_error(self, status: int, data: Any) -> str:
        """Format an error response."""
        error_msg = data
        if isinstance(data, dict):
            error_msg = data.get("error", data)
        return f"Error {status}: {error_msg}"

    def _dict_table(self, data: dict[str, Any]) -> str:
        """Format a single dict as key-value table."""
        if not data:
            return "(empty)"
        max_key = max(len(str(k)) for k in data)
        lines = [f"  {str(k):<{max_key}}  {v}" for k, v in data.items()]
        return "\n".join(lines)

    def _dict_list_table(self, data: list[dict[str, Any]]) -> str:
        """Format a list of dicts as a columnar table."""
        if not data:
            return "(empty)"

        keys = list(data[0].keys())
        widths = {k: len(k) for k in keys}
        for row in data:
            for k in keys:
                widths[k] = max(widths[k], len(str(row.get(k, ""))))

        header = "  ".join(f"{k:<{widths[k]}}" for k in keys)
        separator = "  ".join("-" * widths[k] for k in keys)
        rows = []
        for row in data:
            rows.append("  ".join(
                f"{str(row.get(k, '')):<{widths[k]}}" for k in keys
            ))

        return "\n".join([header, separator, *rows])


if __name__ == "__main__":
    fmt = OutputFormatter()
    print(fmt.format({"name": "test", "value": 42}))
    print()
    print(fmt.format_table([
        {"id": 1, "name": "Alice", "role": "admin"},
        {"id": 2, "name": "Bob", "role": "user"},
    ]))
