import json import sys from typing import Any, Dict, List from datetime import datetime class OutputFormatter: def __init__(self, format_type: str = 'text', quiet: bool = False): self.format_type = format_type self.quiet = quiet def output(self, data: Any, message_type: str = 'response'): if self.quiet and message_type not in ['error', 'result']: return if self.format_type == 'json': self._output_json(data, message_type) elif self.format_type == 'structured': self._output_structured(data, message_type) else: self._output_text(data, message_type) def _output_json(self, data: Any, message_type: str): output = { 'type': message_type, 'timestamp': datetime.now().isoformat(), 'data': data } print(json.dumps(output, indent=2)) def _output_structured(self, data: Any, message_type: str): if isinstance(data, dict): for key, value in data.items(): print(f"{key}: {value}") elif isinstance(data, list): for item in data: print(f"- {item}") else: print(data) def _output_text(self, data: Any, message_type: str): if isinstance(data, (dict, list)): print(json.dumps(data, indent=2)) else: print(data) def error(self, message: str): if self.format_type == 'json': self._output_json({'error': message}, 'error') else: print(f"Error: {message}", file=sys.stderr) def success(self, message: str): if not self.quiet: if self.format_type == 'json': self._output_json({'success': message}, 'success') else: print(message) def info(self, message: str): if not self.quiet: if self.format_type == 'json': self._output_json({'info': message}, 'info') else: print(message) def result(self, data: Any): self.output(data, 'result')