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74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# backend/api_generator/api_factory.py - VERSIÓN CORREGIDA
import json
import logging
from pathlib import Path
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from jinja2 import Environment, FileSystemLoader
from config.settings import config
import pandas as pd

logger = logging.getLogger(__name__)

@dataclass
class APIEndpoint:
    """Define un endpoint de API"""
    path: str
    method: str
    operation: str  # create, read, update, delete, list
    description: str
    parameters: List[Dict[str, Any]]

@dataclass
class APIConfig:
    """Configuración para la generación de API"""
    framework: str  # fastapi, flask, django
    project_name: str
    version: str
    authentication: bool
    pagination: bool
    documentation: bool
    database: str  # sqlite, mysql, postgresql

class APIFactory:
    """Factory para generar APIs completas desde datos"""
    
    def __init__(self):
        # Configurar Jinja2 para plantillas
        template_path = config.TEMPLATES_DIR / "api_templates"
        self.env = Environment(
            loader=FileSystemLoader(template_path),
            trim_blocks=True,
            lstrip_blocks=True
        )
    
    def generate_fastapi(self, data_profile: Any, api_config: APIConfig, 
                        output_dir: Path) -> Dict[str, Any]:
        """Genera una API completa con FastAPI - VERSIÓN CORREGIDA"""
        try:
            # Crear estructura de directorios
            self._create_api_structure(output_dir, api_config.framework)
            
            # OBTENER INFORMACIÓN REAL DE LAS COLUMNAS - CLAVE AQUÍ
            columns_info = self._get_columns_info(data_profile)
            
            # Analizar datos para generar endpoints
            endpoints = self._analyze_data_for_endpoints(data_profile)
            
            # Generar archivos principales CON DATOS REALES
            generated_files = self._generate_fastapi_files(
                endpoints, api_config, output_dir, columns_info, data_profile
            )
            
            logger.info(f"✅ API FastAPI generada en: {output_dir}")
            return {
                "success": True,
                "output_dir": str(output_dir),
                "generated_files": generated_files,
                "endpoints": [e.path for e in endpoints],
                "columns_generated": len(columns_info)
            }
            
        except Exception as e:
            logger.error(f"❌ Error generando API FastAPI: {e}")
            return {"success": False, "error": str(e)}
    
    def _get_columns_info(self, data_profile: Any) -> Dict[str, Dict[str, Any]]:
        """Extrae información REAL de las columnas del DataFrame - FUNCIÓN CLAVE"""
        columns_info = {}
        
        try:
            # Si data_profile tiene el DataFrame directamente
            if hasattr(data_profile, 'current_data') and data_profile.current_data is not None:
                df = data_profile.current_data
            # Si data_profile es el DataFrame mismo
            elif hasattr(data_profile, 'columns') and hasattr(data_profile, 'dtypes'):
                df = data_profile
            else:
                # Intentar obtener datos de otras formas
                logger.warning("No se pudo obtener DataFrame directamente, usando información básica")
                if hasattr(data_profile, 'column_stats'):
                    for col_name, col_stats in data_profile.column_stats.items():
                        columns_info[col_name] = {
                            'type': col_stats.get('type', 'object'),
                            'sql_type': self._map_pandas_to_sql(col_stats.get('type', 'object')),
                            'python_type': self._map_pandas_to_python(col_stats.get('type', 'object')),
                            'nullable': col_stats.get('missing', 0) > 0
                        }
                    return columns_info
                else:
                    # Datos por defecto como fallback
                    return {
                        'id': {'type': 'int64', 'sql_type': 'INTEGER', 'python_type': 'int', 'nullable': False},
                        'nombre': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True},
                        'descripcion': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True}
                    }
            
            # Extraer información REAL de cada columna del DataFrame
            for col_name in df.columns:
                col_dtype = str(df[col_name].dtype)
                columns_info[col_name] = {
                    'type': col_dtype,
                    'sql_type': self._map_pandas_to_sql(col_dtype),
                    'python_type': self._map_pandas_to_python(col_dtype),
                    'nullable': df[col_name].isnull().any(),
                    'unique_count': df[col_name].nunique(),
                    'sample_value': self._get_sample_value(df[col_name])
                }
            
            logger.info(f"📊 Extraída información de {len(columns_info)} columnas")
            return columns_info
            
        except Exception as e:
            logger.error(f"❌ Error extrayendo información de columnas: {e}")
            # Datos de fallback para evitar errores
            return {
                'id': {'type': 'int64', 'sql_type': 'INTEGER', 'python_type': 'int', 'nullable': False},
                'nombre': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True}
            }
    
    def _get_sample_value(self, series):
        """Obtiene un valor de muestra no nulo de la serie"""
        try:
            # Buscar el primer valor no nulo
            non_null_values = series.dropna()
            if len(non_null_values) > 0:
                sample = non_null_values.iloc[0]
                # Truncar si es muy largo
                if isinstance(sample, str) and len(sample) > 50:
                    return sample[:50] + "..."
                return sample
            return None
        except:
            return None
    
    def _map_pandas_to_sql(self, pandas_type: str) -> str:
        """Mapea tipos de pandas a tipos SQL - CORREGIDO"""
        type_mapping = {
            'int64': 'INTEGER',
            'int32': 'INTEGER',
            'float64': 'REAL',
            'float32': 'REAL',
            'object': 'TEXT',
            'bool': 'BOOLEAN',
            'boolean': 'BOOLEAN',
            'datetime64[ns]': 'TIMESTAMP',
            'datetime64[ms]': 'TIMESTAMP',
            'category': 'TEXT'
        }
        return type_mapping.get(pandas_type, 'TEXT')
    
    def _map_pandas_to_python(self, pandas_type: str) -> str:
        """Mapea tipos de pandas a tipos de Python/FastAPI - CORREGIDO"""
        type_mapping = {
            'int64': 'int',
            'int32': 'int',
            'float64': 'float',
            'float32': 'float',
            'object': 'str',
            'bool': 'bool',
            'boolean': 'bool',
            'datetime64[ns]': 'datetime',
            'datetime64[ms]': 'datetime',
            'category': 'str'
        }
        return type_mapping.get(pandas_type, 'str')
    
    def _create_api_structure(self, output_dir: Path, framework: str):
        """Crea la estructura de directorios de la API"""
        directories = [
            output_dir / "app",
            output_dir / "app" / "api",
            output_dir / "tests",
        ]
        
        for directory in directories:
            directory.mkdir(parents=True, exist_ok=True)
    
    def _analyze_data_for_endpoints(self, data_profile: Any) -> List[APIEndpoint]:
        """Analiza los datos para generar endpoints automáticamente"""
        endpoints = []
        
        # Detectar entidades principales basadas en nombres de columnas
        entities = self._detect_entities(data_profile)
        
        for entity in entities:
            entity_name = entity["name"]
            entity_columns = entity["columns"]
            
            # Endpoint para listar todos los registros
            endpoints.append(APIEndpoint(
                path=f"/api/{entity_name}/",
                method="GET",
                operation="list",
                description=f"Listar todos los {entity_name}",
                parameters=[
                    {"name": "skip", "type": "int", "default": 0, "description": "Número de registros a saltar"},
                    {"name": "limit", "type": "int", "default": 100, "description": "Número máximo de registros a retornar"}
                ]
            ))
            
            # Endpoint para obtener un registro por ID
            endpoints.append(APIEndpoint(
                path=f"/api/{entity_name}/{{item_id}}",
                method="GET", 
                operation="read",
                description=f"Obtener un {entity_name} por ID",
                parameters=[
                    {"name": "item_id", "type": "int", "description": "ID del registro"}
                ]
            ))
            
            # Endpoint para crear nuevo registro
            endpoints.append(APIEndpoint(
                path=f"/api/{entity_name}/",
                method="POST",
                operation="create",
                description=f"Crear un nuevo {entity_name}",
                parameters=entity_columns
            ))
            
            # Endpoint para actualizar registro
            endpoints.append(APIEndpoint(
                path=f"/api/{entity_name}/{{item_id}}",
                method="PUT",
                operation="update", 
                description=f"Actualizar un {entity_name} existente",
                parameters=entity_columns
            ))
            
            # Endpoint para eliminar registro
            endpoints.append(APIEndpoint(
                path=f"/api/{entity_name}/{{item_id}}",
                method="DELETE",
                operation="delete",
                description=f"Eliminar un {entity_name}",
                parameters=[
                    {"name": "item_id", "type": "int", "description": "ID del registro a eliminar"}
                ]
            ))
        
        return endpoints
    
    def _detect_entities(self, data_profile: Any) -> List[Dict[str, Any]]:
        """Detecta entidades automáticamente basado en el perfil de datos"""
        entities = []
        
        # Obtener información de columnas REAL
        columns_info = self._get_columns_info(data_profile)
        
        if columns_info:
            columns = []
            for col_name, col_info in columns_info.items():
                column_def = {
                    "name": col_name,
                    "type": col_info['python_type'],
                    "required": not col_info['nullable'],
                    "description": f"Campo {col_name} - Tipo: {col_info['type']}",
                    "sql_type": col_info['sql_type']
                }
                columns.append(column_def)
            
            # Detectar primary key
            primary_key = self._detect_primary_key(data_profile)
            
            entities.append({
                "name": "items",  # Nombre por defecto
                "columns": columns,
                "primary_key": primary_key,
                "total_columns": len(columns)
            })
        
        return entities
    
    def _detect_primary_key(self, data_profile: Any) -> str:
        """Detecta la columna que probablemente sea la primary key - MEJORADO"""
        try:
            if hasattr(data_profile, 'current_data') and data_profile.current_data is not None:
                df = data_profile.current_data
            elif hasattr(data_profile, 'columns') and hasattr(data_profile, 'dtypes'):
                df = data_profile
            else:
                return "id"  # Por defecto
            
            # Buscar columnas que sean buenas candidatas a PK
            for col_name in df.columns:
                col_lower = col_name.lower()
                
                # Criterios para ser primary key
                is_id_like = any(keyword in col_lower for keyword in ['id', 'code', 'key', 'pk'])
                is_unique = df[col_name].nunique() == len(df)
                has_no_nulls = not df[col_name].isnull().any()
                
                if is_id_like and is_unique and has_no_nulls:
                    logger.info(f"🔑 Primary key detectada: {col_name}")
                    return col_name
            
            # Si no se encuentra, usar la primera columna única
            for col_name in df.columns:
                if df[col_name].nunique() == len(df) and not df[col_name].isnull().any():
                    logger.info(f"🔑 Primary key alternativa detectada: {col_name}")
                    return col_name
            
            # Por defecto, usar 'id'
            return "id"
            
        except Exception as e:
            logger.warning(f"⚠️ Error detectando primary key: {e}")
            return "id"
    
    def _generate_fastapi_files(self, endpoints: List[APIEndpoint], 
                               api_config: APIConfig, output_dir: Path,
                               columns_info: Dict, data_profile: Any) -> List[str]:
        """Genera los archivos específicos de FastAPI CON DATOS REALES"""
        generated_files = []
        
        # Contexto para plantillas - INCLUYENDO INFORMACIÓN REAL DE COLUMNAS
        context = {
            "project_name": api_config.project_name,
            "version": api_config.version,
            "endpoints": endpoints,
            "authentication": api_config.authentication,
            "pagination": api_config.pagination,
            "database": api_config.database,
            # INFORMACIÓN REAL DE DATOS - CLAVE PARA QUE FUNCIONE
            "columns": columns_info,
            "columns_info": columns_info,  # alias para compatibilidad
            "primary_key": self._detect_primary_key(data_profile),
            "total_columns": len(columns_info),
            "has_data": len(columns_info) > 0
        }
        
        # Archivos a generar
        templates_to_generate = {
            "main.py.j2": "app/main.py",
            "models.py.j2": "app/models.py", 
            "schemas.py.j2": "app/schemas.py",
            "database.py.j2": "app/database.py",
            "api_endpoints.py.j2": "app/api/api.py",
            "requirements.txt.j2": "requirements.txt",
            "Dockerfile.j2": "Dockerfile",
            "README.md.j2": "README.md"
        }
        
        for template_name, output_path in templates_to_generate.items():
            try:
                template = self.env.get_template(template_name)
                content = template.render(**context)  # Usar ** para expandir el contexto
                
                file_path = output_dir / output_path
                file_path.parent.mkdir(parents=True, exist_ok=True)
                
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                generated_files.append(str(file_path))
                logger.info(f"✅ Generado: {file_path}")
                
            except Exception as e:
                logger.error(f"❌ Error generando {template_name}: {e}")
                # Crear archivo básico como fallback
                self._create_fallback_file(file_path, template_name)
        
        return generated_files
    
    def _create_fallback_file(self, file_path: Path, template_name: str):
        """Crea un archivo básico como fallback si la plantilla falla"""
        try:
            if template_name == "models.py.j2":
                content = """from sqlalchemy import Column, Integer, String, Text, DateTime
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime

Base = declarative_base()

class Item(Base):
    __tablename__ = "items"
    
    id = Column(Integer, primary_key=True, index=True)
    nombre = Column(String(100))
    descripcion = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
"""
            elif template_name == "schemas.py.j2":
                content = """from pydantic import BaseModel
from datetime import datetime
from typing import Optional

class ItemBase(BaseModel):
    nombre: str
    descripcion: Optional[str] = None

class ItemCreate(ItemBase):
    pass

class ItemUpdate(ItemBase):
    pass

class Item(ItemBase):
    id: int
    created_at: datetime
    
    class Config:
        from_attributes = True
"""
            else:
                content = f"# Fallback para {template_name}\n# Error al generar plantilla"
            
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
                
            logger.info(f"📄 Archivo fallback creado: {file_path}")
            
        except Exception as e:
            logger.error(f"❌ Error creando archivo fallback: {e}")

# Función de conveniencia
def create_api_factory() -> APIFactory:
    """Crea una instancia del factory de APIs"""
    return APIFactory()