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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
"""
Pure LLM-based transformation engine.
Implements simplified decision logic: template-based for known ERP+Entity, pure LLM for unknown.
"""

import logging
import polars as pl
from typing import Dict, Any, Optional, Tuple, Union, List
from pathlib import Path
from enum import Enum

from .data_processor import DataProcessor, FileFormat
from .template_loader import TemplateLoader
from .llm_handler_pure import create_pure_llm_handler
from .models import EntityType, TransformationRequest, TransformationResult, TransformationMode

logger = logging.getLogger(__name__)


class PureTransformationEngine:
    """Pure LLM-based transformation engine with simplified decision logic."""
    
    def __init__(self,
                 template_path: Optional[Path] = None,
                 memory_limit: str = "1GB"):
        """Initialize pure transformation engine.
        
        Args:
            template_path: Path to template.json file
            memory_limit: Memory limit for data processing
        """
        self.data_processor = DataProcessor()
        self.template_loader = TemplateLoader(template_path)
        
        # Initialize Pure LLM handler
        self.pure_llm_handler = create_pure_llm_handler()
    
    def transform(self, request: TransformationRequest) -> TransformationResult:
        """Transform data using pure LLM approach.
        
        Args:
            request: Transformation request
            
        Returns:
            Transformation result
        """
        try:
            # Step 1: Load data
            input_df = self._load_data(request)
            if input_df is None:
                return TransformationResult(
                    success=False,
                    message="Failed to load input data"
                )
            
            logger.info(f"Loaded data: {len(input_df)} rows, {len(input_df.columns)} columns")
            
            # Step 2: Normalize column names
            input_df = self.data_processor.normalize_column_names(input_df)
            
            # Step 3: Simplified decision logic
            if not request.auto_select_erp and not request.auto_select_entity:
                # CASE 1: ERP and Entity Known - Direct template mapping
                logger.info("Using template-based transformation (ERP and Entity known)")
                return self._template_based_transform(input_df, request.erp, request.entity)
            else:
                # CASE 2: ERP or Entity Unknown - Pure LLM mapping
                logger.info("Using pure LLM transformation (ERP or Entity unknown)")
                return self._pure_llm_transform(input_df, request)
                
        except Exception as e:
            logger.error(f"Pure transformation failed: {e}")
            return TransformationResult(
                success=False,
                message=f"Pure transformation error: {str(e)}"
            )
    
    def _load_data(self, request: TransformationRequest) -> Optional[pl.DataFrame]:
        """Load data from request.
        
        Args:
            request: Transformation request
            
        Returns:
            Loaded DataFrame or None if failed
        """
        if request.file_data is None:
            return None
            
        try:
            if isinstance(request.file_data, (str, Path)):
                # File path
                return self.data_processor.load_file(request.file_data, request.file_format)
            elif isinstance(request.file_data, bytes):
                # File bytes
                if request.file_format is None:
                    raise ValueError("File format required for bytes data")
                return self.data_processor.load_from_bytes(
                    request.file_data, request.file_format
                )
            else:
                raise ValueError(f"Unsupported file_data type: {type(request.file_data)}")
                
        except Exception as e:
            logger.error(f"Failed to load data: {e}")
            return None
    
    def _template_based_transform(self, input_df: pl.DataFrame, erp: str, entity: str) -> TransformationResult:
        """Perform template-based transformation (same as original logic).
        
        Args:
            input_df: Input DataFrame
            erp: ERP system name
            entity: Entity type
            
        Returns:
            Transformation result
        """
        logger.info(f"Template-based transformation: {erp} -> {entity}")
        
        try:
            # Get mapping from template
            mapping = self.template_loader.get_entity_mapping(erp, entity)
            if not mapping:
                return TransformationResult(
                    success=False,
                    message=f"No mapping found for {erp} -> {entity}"
                )
            
            # Apply transformation
            output_df = self._apply_column_mapping(input_df, mapping, entity)
            
            return TransformationResult(
                success=True,
                data=output_df,
                detected_erp=erp,
                detected_entity=entity,
                transformation_mode=TransformationMode.TEMPLATE_BASED,
                confidence_score=1.0,
                message=f"Successfully transformed using template mapping",
                column_mappings=mapping
            )
            
        except Exception as e:
            logger.error(f"Template-based transformation failed: {e}")
            return TransformationResult(
                success=False,
                message=f"Template transformation error: {str(e)}"
            )
    
    def _pure_llm_transform(self, input_df: pl.DataFrame, request: TransformationRequest) -> TransformationResult:
        """Perform pure LLM-based transformation.
        
        Args:
            input_df: Input DataFrame
            request: Transformation request
            
        Returns:
            Transformation result
        """
        logger.info("Pure LLM transformation")
        
        try:
            columns = list(input_df.columns)
            
            # Determine target entity - if not specified, let LLM detect it
            if request.entity:
                target_entity = request.entity
                logger.info(f"Using specified entity: {target_entity}")
            else:
                # Let LLM detect the entity type based on column names
                target_entity = self._detect_entity_with_llm(columns)
                logger.info(f"LLM detected entity: {target_entity}")
            
            # Get CDF schema for target entity
            cdf_schema = self.template_loader.get_cdf_schema(target_entity)
            if not cdf_schema:
                return TransformationResult(
                    success=False,
                    message=f"No CDF schema found for entity: {target_entity}"
                )
            
            # Use Pure LLM to infer mapping
            llm_mapping = self.pure_llm_handler.infer_mapping_pure(columns, cdf_schema, target_entity)
            
            if not llm_mapping:
                return TransformationResult(
                    success=False,
                    message="Pure LLM mapping failed after all retry attempts"
                )
            
            # Apply LLM-generated mapping
            output_df = self._apply_column_mapping(input_df, llm_mapping, target_entity)
            
            # Calculate confidence based on mapping coverage
            mapping_coverage = len(llm_mapping) / len(cdf_schema) if cdf_schema else 0
            confidence_score = min(0.9, 0.6 + (mapping_coverage * 0.3))  # 0.6-0.9 range
            
            return TransformationResult(
                success=True,
                data=output_df,
                detected_erp="Unknown (Pure LLM)",
                detected_entity=target_entity,
                transformation_mode=TransformationMode.AI_ASSISTED,
                confidence_score=confidence_score,
                message=f"Successfully transformed using Pure LLM mapping ({len(llm_mapping)} fields mapped)",
                column_mappings=llm_mapping
            )
            
        except Exception as e:
            logger.error(f"Pure LLM transformation failed: {e}")
            return TransformationResult(
                success=False,
                message=f"Pure LLM transformation error: {str(e)}"
            )
    
    def _detect_entity_with_llm(self, columns: List[str]) -> str:
        """Use LLM to detect the most likely entity type based on column names.
        
        Args:
            columns: List of column names from the data
            
        Returns:
            Detected entity type
        """
        try:
            # Get available entity types
            available_entities = [e.value for e in EntityType]
            
            # Use LLM to detect entity type
            detected_entity = self.pure_llm_handler.detect_entity_type(columns, available_entities)
            
            if detected_entity and detected_entity in available_entities:
                return detected_entity
            else:
                # Fallback to sales_orders if detection fails
                logger.warning(f"LLM entity detection failed or returned invalid entity: {detected_entity}. Using fallback.")
                return "sales_orders"
                
        except Exception as e:
            logger.error(f"Entity detection failed: {e}")
            # Fallback to sales_orders if detection fails
            return "sales_orders"
    
    def _apply_column_mapping(self, input_df: pl.DataFrame, mapping: Dict[str, str], entity: str) -> pl.DataFrame:
        """Apply column mapping to transform DataFrame.
        
        Args:
            input_df: Input DataFrame
            mapping: Column mapping dictionary
            entity: Target entity type
            
        Returns:
            Transformed DataFrame
        """
        # Step 1: Rename columns according to mapping
        rename_dict = {}
        for source_col, target_col in mapping.items():
            # Find matching column (case-insensitive)
            for df_col in input_df.columns:
                if df_col.lower() == source_col.lower():
                    rename_dict[df_col] = target_col
                    break
        
        output_df = input_df.rename(rename_dict)
        
        # Step 2: Get expected CDF schema and successfully mapped columns
        expected_columns = self.template_loader.get_cdf_schema(entity)
        mapped_columns = list(mapping.values())  # Columns that were successfully mapped
        
        # Step 3: Determine final column set - prioritize mapped columns, then add missing CDF columns
        final_columns = []
        
        # Add all successfully mapped columns first (preserve LLM mapping results)
        for col in mapped_columns:
            if col in output_df.columns:
                final_columns.append(col)
        
        # Add any missing essential CDF columns with null values
        for col in expected_columns:
            if col not in final_columns:
                if col not in output_df.columns:
                    output_df = output_df.with_columns(pl.lit(None).alias(col))
                final_columns.append(col)
        
        # Step 4: Select columns in logical order (mapped first, then missing CDF columns)
        output_df = output_df.select(final_columns)
        
        # Step 5: Apply data type conversions
        output_df = self._apply_data_types(output_df, entity)
        
        return output_df
    
    def _apply_data_types(self, df: pl.DataFrame, entity: str, output_format: str = "json") -> pl.DataFrame:
        """Apply appropriate data types and formatting based on CDF schema and output format.
        
        Args:
            df: DataFrame to type-convert
            entity: Entity type
            output_format: Output format (json, csv, excel, api, database)
            
        Returns:
            DataFrame with proper data types and formatting
        """
        # Define data type mappings for each entity
        type_mappings = {
            "sales_orders": {
                "order_date": pl.Date,
                "total_amount": pl.Float64,
                "quantity": pl.Int64,
                "unit_price": pl.Float64,
                "line_total": pl.Float64
            },
            "customers": {
                "is_company": pl.Boolean,
                "created_date": pl.Datetime,
                "last_modified": pl.Datetime
            },
            "invoices": {
                "invoice_date": pl.Date,
                "total_amount": pl.Float64,
                "due_date": pl.Date,
                "quantity": pl.Int64,
                "unit_price": pl.Float64,
                "line_total": pl.Float64
            },
            "purchase_orders": {
                "po_date": pl.Date,
                "total_amount": pl.Float64,
                "expected_receipt_date": pl.Date,
                "quantity": pl.Int64,
                "unit_price": pl.Float64,
                "line_total": pl.Float64
            },
            "inventory_items": {
                "base_price": pl.Float64,
                "cost_price": pl.Float64,
                "is_active": pl.Boolean,
                "quantity_on_hand": pl.Int64,
                "reorder_point": pl.Int64
            }
        }
        
        entity_types = type_mappings.get(entity, {})
        
        # Apply type conversions with proper null handling
        for column, dtype in entity_types.items():
            if column in df.columns:
                try:
                    # Handle null/empty values before type conversion
                    if dtype == pl.Date:
                        df = df.with_columns(
                            pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
                            .then(None)
                            .otherwise(pl.col(column).str.to_date(strict=False))
                            .alias(column)
                        )
                    elif dtype == pl.Datetime:
                        df = df.with_columns(
                            pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
                            .then(None)
                            .otherwise(pl.col(column).str.to_datetime(strict=False))
                            .alias(column)
                        )
                    elif dtype == pl.Boolean:
                        df = df.with_columns(
                            pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
                            .then(None)
                            .otherwise(pl.col(column).cast(pl.Boolean, strict=False))
                            .alias(column)
                        )
                    elif dtype in [pl.Int64, pl.Float64]:
                        df = df.with_columns(
                            pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
                            .then(None)
                            .otherwise(pl.col(column).cast(dtype, strict=False))
                            .alias(column)
                        )
                except Exception as e:
                    logger.warning(f"Failed to convert column {column} to {dtype}: {e}")
                    # Keep original column if conversion fails
                    continue
        
        # Apply format-specific transformations
        df = self._apply_format_consistency(df, entity, output_format)
        
        return df
    
    def _apply_format_consistency(self, df: pl.DataFrame, entity: str, output_format: str) -> pl.DataFrame:
        """Apply format consistency rules based on ERP-CDF-Mapping guidelines.
        
        Args:
            df: DataFrame to format
            entity: Entity type
            output_format: Output format (json, csv, excel, api, database)
            
        Returns:
            DataFrame with consistent formatting
        """
        try:
            # Date field formatting
            date_columns = self._get_date_columns(entity)
            for col in date_columns:
                if col in df.columns:
                    try:
                        if output_format in ["csv", "excel"]:
                            # Human-readable format: dd-MMMM-yyyy (e.g., 04-August-2025)
                            df = df.with_columns(
                                pl.when(pl.col(col).is_null())
                                .then(None)
                                .otherwise(pl.col(col).dt.strftime("%d-%B-%Y"))
                                .alias(col)
                            )
                        else:
                            # API/Database format: ISO yyyy-MM-dd
                            df = df.with_columns(
                                pl.when(pl.col(col).is_null())
                                .then(None)
                                .otherwise(pl.col(col).dt.strftime("%Y-%m-%d"))
                                .alias(col)
                            )
                    except Exception as e:
                        logger.warning(f"Failed to format date column {col}: {e}")
            
            # Decimal field formatting (currency, unit prices, totals)
            decimal_columns = self._get_decimal_columns(entity)
            for col in decimal_columns:
                if col in df.columns:
                    try:
                        # Ensure two decimal places (e.g., 1249.00) - only for non-null numeric values
                        df = df.with_columns(
                            pl.when(pl.col(col).is_null() | pl.col(col).is_nan())
                            .then(None)
                            .otherwise(pl.col(col).round(2))
                            .alias(col)
                        )
                    except Exception as e:
                        logger.warning(f"Failed to format decimal column {col}: {e}")
            
            # Boolean field formatting
            boolean_columns = self._get_boolean_columns(entity)
            for col in boolean_columns:
                if col in df.columns:
                    try:
                        if output_format == "database":
                            # Database format: 1/0
                            df = df.with_columns(
                                pl.when(pl.col(col).is_null())
                                .then(None)
                                .otherwise(pl.col(col).cast(pl.Int8))
                                .alias(col)
                            )
                        else:
                            # JSON/API format: true/false
                            df = df.with_columns(
                                pl.when(pl.col(col).is_null())
                                .then(None)
                                .otherwise(pl.col(col).cast(pl.Boolean))
                                .alias(col)
                            )
                    except Exception as e:
                        logger.warning(f"Failed to format boolean column {col}: {e}")
            
            # Text field formatting (UTF-8 encoding)
            text_columns = self._get_text_columns(entity)
            for col in text_columns:
                if col in df.columns:
                    try:
                        # Ensure UTF-8 encoding and proper escaping
                        df = df.with_columns(
                            pl.when(pl.col(col).is_null())
                            .then(None)
                            .otherwise(pl.col(col).str.strip_chars())
                            .alias(col)
                        )
                    except Exception as e:
                        logger.warning(f"Failed to format text column {col}: {e}")
            
            return df
            
        except Exception as e:
            logger.error(f"Format consistency failed: {e}")
            return df  # Return original DataFrame if formatting fails
    
    def _get_date_columns(self, entity: str) -> List[str]:
        """Get date columns for entity."""
        date_mappings = {
            "sales_orders": ["order_date"],
            "customers": ["created_date", "last_modified"],
            "invoices": ["invoice_date", "due_date"],
            "purchase_orders": ["po_date", "expected_receipt_date"],
            "inventory_items": []
        }
        return date_mappings.get(entity, [])
    
    def _get_decimal_columns(self, entity: str) -> List[str]:
        """Get decimal columns for entity (currency, prices, totals)."""
        decimal_mappings = {
            "sales_orders": ["total_amount", "unit_price", "line_total"],
            "customers": [],
            "invoices": ["total_amount", "unit_price", "line_total"],
            "purchase_orders": ["total_amount", "unit_price", "line_total"],
            "inventory_items": ["base_price", "cost_price"]
        }
        return decimal_mappings.get(entity, [])
    
    def _get_boolean_columns(self, entity: str) -> List[str]:
        """Get boolean columns for entity."""
        boolean_mappings = {
            "sales_orders": [],
            "customers": ["is_company"],
            "invoices": [],
            "purchase_orders": [],
            "inventory_items": ["is_active"]
        }
        return boolean_mappings.get(entity, [])
    
    def _get_text_columns(self, entity: str) -> List[str]:
        """Get text columns for entity."""
        text_mappings = {
            "sales_orders": ["customer_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
            "customers": ["customer_id", "customer_name", "contact_email", "phone_number", "alt_phone", "status", "currency", "address_type", "address_line1", "city", "state", "postal_code", "country"],
            "invoices": ["invoice_id", "customer_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
            "purchase_orders": ["po_id", "vendor_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
            "inventory_items": ["item_id", "item_name", "description", "purchase_description", "sales_description", "unit_type", "preferred_vendor_id"]
        }
        return text_mappings.get(entity, [])
    
    def analyze_data(self, file_data: Union[str, Path, bytes], 
                    file_format: Optional[FileFormat] = None) -> Dict[str, Any]:
        """Analyze input data and provide insights.
        
        Args:
            file_data: File path, bytes, or data
            file_format: File format (auto-detected if None)
            
        Returns:
            Analysis results
        """
        try:
            # Load data
            request = TransformationRequest(file_data=file_data, file_format=file_format)
            input_df = self._load_data(request)
            
            if input_df is None:
                return {"error": "Failed to load data"}
            
            # Normalize columns
            input_df = self.data_processor.normalize_column_names(input_df)
            
            # Get basic info
            column_info = self.data_processor.get_column_info(input_df)
            
            # For pure LLM engine, we don't do ERP detection
            # Just provide basic analysis
            return {
                "column_info": column_info,
                "erp_entity_suggestions": [
                    {
                        "entity": "sales_orders",
                        "erp": "Unknown (will use Pure LLM)",
                        "confidence": 0.8,
                        "above_threshold": True
                    }
                ],
                "available_entities": [e.value for e in EntityType],
                "available_erps": ["Unknown (Pure LLM)"] + self.template_loader.get_erp_names(),
                "note": "Pure LLM engine will analyze your data using AI without ERP detection"
            }
            
        except Exception as e:
            logger.error(f"Data analysis failed: {e}")
            return {"error": f"Analysis failed: {str(e)}"}
    
    def close(self):
        """Close resources."""
        if self.data_processor:
            self.data_processor.close()