"""
T216: Sistema de Reportes JSON/CSV/Markdown
export_system_report - Exporta métricas completas del sistema
"""

import json
import csv
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Any, Optional


class SystemReporter:
    """Genera reportes del sistema en múltiples formatos."""
    
    def __init__(self, output_dir: str = None):
        self.output_dir = output_dir or os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 
            'cloud', 'reports'
        )
        os.makedirs(self.output_dir, exist_ok=True)
        
    def export_system_report(self, format_type: str = 'json', 
                             include_metrics: bool = True,
                             include_history: bool = True,
                             include_library: bool = True) -> str:
        """
        Exporta reporte completo del sistema.
        
        Args:
            format_type: 'json', 'csv', o 'markdown'
            include_metrics: Incluir métricas de sistema
            include_history: Incluir historial de generaciones
            include_library: Incluir estadísticas de librería
            
        Returns:
            Ruta al archivo exportado
        """
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        data = self._collect_system_data(include_metrics, include_history, include_library)
        
        if format_type.lower() == 'json':
            return self._export_json(data, timestamp)
        elif format_type.lower() == 'csv':
            return self._export_csv(data, timestamp)
        elif format_type.lower() == 'markdown':
            return self._export_markdown(data, timestamp)
        else:
            raise ValueError(f"Formato no soportado: {format_type}")
    
    def _collect_system_data(self, include_metrics: bool, 
                           include_history: bool, 
                           include_library: bool) -> Dict[str, Any]:
        """Recolecta todos los datos del sistema."""
        data = {
            'timestamp': datetime.now().isoformat(),
            'version': '2.0.0',
            'block': 'T216-T235'
        }
        
        if include_metrics:
            data['metrics'] = self._get_system_metrics()
            
        if include_history:
            data['generation_history'] = self._get_generation_history()
            
        if include_library:
            data['library_stats'] = self._get_library_stats()
            
        return data
    
    def _get_system_metrics(self) -> Dict[str, Any]:
        """Obtiene métricas del sistema."""
        try:
            from ..mcp_wrapper import AbletonMCPWrapper
            wrapper = AbletonMCPWrapper()
            
            return {
                'total_generations': wrapper._call_tool('ableton-mcp-ai_get_system_metrics', {}),
                'sample_coverage': wrapper._call_tool('ableton-mcp-ai_get_sample_coverage_report', {}),
                'diversity_memory': wrapper._call_tool('ableton-mcp-ai_get_diversity_memory_stats', {}),
                'current_session': wrapper._call_tool('ableton-mcp-ai_get_session_info', {})
            }
        except Exception as e:
            return {'error': str(e)}
    
    def _get_generation_history(self) -> List[Dict[str, Any]]:
        """Obtiene historial de generaciones."""
        try:
            from ..mcp_wrapper import AbletonMCPWrapper
            wrapper = AbletonMCPWrapper()
            
            history = wrapper._call_tool('ableton-mcp-ai_get_generation_history', {'limit': 50})
            return history if isinstance(history, list) else []
        except:
            return []
    
    def _get_library_stats(self) -> Dict[str, Any]:
        """Obtiene estadísticas de librería."""
        try:
            from ..mcp_wrapper import AbletonMCPWrapper
            wrapper = AbletonMCPWrapper()
            
            return wrapper._call_tool('ableton-mcp-ai_get_sample_library_stats', {})
        except:
            return {}
    
    def _export_json(self, data: Dict[str, Any], timestamp: str) -> str:
        """Exporta a JSON."""
        filepath = os.path.join(self.output_dir, f'system_report_{timestamp}.json')
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        return filepath
    
    def _export_csv(self, data: Dict[str, Any], timestamp: str) -> str:
        """Exporta a CSV (generaciones principales)."""
        filepath = os.path.join(self.output_dir, f'system_report_{timestamp}.csv')
        
        # Preparar datos CSV desde historial
        history = data.get('generation_history', [])
        if history and isinstance(history, list) and len(history) > 0:
            fieldnames = list(history[0].keys()) if isinstance(history[0], dict) else ['data']
            
            with open(filepath, 'w', newline='', encoding='utf-8') as f:
                writer = csv.DictWriter(f, fieldnames=fieldnames)
                writer.writeheader()
                for row in history:
                    if isinstance(row, dict):
                        writer.writerow(row)
        else:
            # CSV vacío con metadatos
            with open(filepath, 'w', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerow(['timestamp', 'metric', 'value'])
                writer.writerow([data.get('timestamp', ''), 'total_generations', 'N/A'])
        
        return filepath
    
    def _export_markdown(self, data: Dict[str, Any], timestamp: str) -> str:
        """Exporta a Markdown."""
        filepath = os.path.join(self.output_dir, f'system_report_{timestamp}.md')
        
        lines = [
            f"# AbletonMCP-AI System Report",
            f"**Generated:** {data.get('timestamp', 'N/A')}",
            f"**Version:** {data.get('version', 'N/A')}",
            f"**Block:** {data.get('block', 'N/A')}",
            "",
            "## System Metrics",
            "",
            f"```json",
            f"{json.dumps(data.get('metrics', {}), indent=2)}",
            f"```",
            "",
            "## Generation History",
            f"Total generations recorded: {len(data.get('generation_history', []))}",
            "",
            "## Library Statistics",
            "",
            f"```json",
            f"{json.dumps(data.get('library_stats', {}), indent=2)}",
            f"```",
            "",
            "---",
            "*Report generated by AbletonMCP-AI Block 6 - T216*"
        ]
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
        
        return filepath


def export_system_report(format: str = 'json', 
                         include_metadata: bool = True) -> Dict[str, Any]:
    """
    Función pública para exportar reporte del sistema.
    
    T108: Exporta reporte completo del sistema para análisis externo.
    
    Args:
        format: 'json', 'csv', o 'markdown'
        include_metadata: Incluir metadata BPM/key en archivos
        
    Returns:
        Dict con ruta al archivo exportado y metadatos
    """
    reporter = SystemReporter()
    
    try:
        filepath = reporter.export_system_report(
            format_type=format,
            include_metrics=True,
            include_history=True,
            include_library=True
        )
        
        return {
            'success': True,
            'filepath': filepath,
            'format': format,
            'timestamp': datetime.now().isoformat(),
            'size_bytes': os.path.getsize(filepath) if os.path.exists(filepath) else 0
        }
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'format': format
        }


if __name__ == '__main__':
    # Test del sistema de reportes
    for fmt in ['json', 'csv', 'markdown']:
        result = export_system_report(format=fmt)
        print(f"Format {fmt}: {result}")
