"""Adapter for formatting restructuring recommendations as Python code."""
from typing import Dict, Any, List, Optional, Set
import os
import re

from .base import BaseDataModelAdapter, register_model_adapter

@register_model_adapter
class PythonAdapter(BaseDataModelAdapter):
    """Adapter for formatting restructuring recommendations as Python code."""
    
    def format_recommendations(self, recommendations: List[Dict[str, Any]], metadata: Dict[str, Any], **kwargs) -> str:
        """
        Format restructuring recommendations as Python code using pandas.
        
        Args:
            recommendations: List of restructuring recommendations
            metadata: Metadata dictionary
            **kwargs: Additional parameters
            
        Returns:
            Python code as a string
        """
        # Sort recommendations by type and severity
        severity_order = {"high": 0, "medium": 1, "low": 2}
        sorted_recommendations = sorted(
            recommendations, 
            key=lambda x: (x.get("type", ""), severity_order.get(x.get("severity", "low"), 3))
        )
        
        # Group recommendations by type
        grouped: Dict[str, List[Dict[str, Any]]] = {}
        for rec in sorted_recommendations:
            rec_type = rec.get("type", "other")
            if rec_type not in grouped:
                grouped[rec_type] = []
            grouped[rec_type].append(rec)
        
        # Build Python script
        file_path = kwargs.get('file_path', 'data.csv')
        file_name = os.path.basename(file_path)
        python_lines = [
            "#!/usr/bin/env python3",
            "# Python script for restructuring CSV data",
            "# Generated by csvdiffgpt",
            f"# Original file: {file_name}",
            "",
            "import pandas as pd",
            "import numpy as np",
            "from pathlib import Path",
            "",
            "def restructure_csv():",
            f"    # Load the original CSV file",
            f"    df = pd.read_csv('{file_name}', sep='{metadata.get('separator', ',')}')",
            f"    print(f'Loaded {{len(df)}} rows and {{len(df.columns)}} columns from {file_name}')",
            "",
            "    # Create output directory if it doesn't exist",
            "    output_dir = Path('restructured_data')",
            "    output_dir.mkdir(exist_ok=True)",
            "",
            "    # Store transformed dataframes",
            "    dataframes = {",
            "        'main': df.copy()",
            "    }"
        ]
        
        # Add transformation code for each recommendation group
        for group_type, group_recs in grouped.items():
            if group_recs:
                python_lines.append("")
                python_lines.append(f"    # {group_type.upper()} TRANSFORMATIONS")
                python_lines.append(f"    print('Applying {len(group_recs)} {group_type} transformations...')")
                python_lines.append("")
                
                for i, rec in enumerate(group_recs):
                    # Add recommendation comment
                    python_lines.append(f"    # Recommendation {i+1}: {rec.get('description', '')}")
                    
                    # Extract Python code from the recommendation
                    py_code = rec.get("python_code", "# No Python code provided for this recommendation")
                    
                    # Indent the code properly
                    indented_code = ["    " + line for line in py_code.split("\n")]
                    python_lines.extend(indented_code)
                    
                    python_lines.append("")
        
        # Add code to save all dataframes
        python_lines.extend([
            "    # Save transformed dataframes",
            "    for name, df in dataframes.items():",
            "        output_file = output_dir / f'{name}.csv'",
            "        df.to_csv(output_file, index=False)",
            "        print(f'Saved {name} dataframe to {output_file} ({len(df)} rows, {len(df.columns)} columns)')",
            "",
            "    print('Restructuring complete!')",
            "",
            "if __name__ == '__main__':",
            "    restructure_csv()"
        ])
        
        return "\n".join(python_lines)