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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4293da0
 
 
 
 
 
 
 
 
 
 
 
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
"""
Pure LLM-based mapping handler with enhanced template context.
Provides AI-assisted mapping using rich examples from template.json.
"""

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

logger = logging.getLogger(__name__)


class PureLLMHandler:
    """Pure LLM handler with enhanced template context for better mapping accuracy."""
    
    def __init__(self, 
                 api_key: Optional[str] = None,
                 model_name: str = "meta-llama/llama-4-maverick-17b-128e-instruct",
                 temperature: float = 0.2,
                 max_tokens: int = 2048,
                 max_retries: int = 5):
        """Initialize Pure LLM handler with enhanced context.
        
        Args:
            api_key: Groq API key (from env if None)
            model_name: Model to use
            temperature: Sampling temperature (0.2 for consistent but creative mapping)
            max_tokens: Maximum tokens in response
            max_retries: Maximum retry attempts (5 as requested)
        """
        self.api_key = api_key or os.getenv("GROQ_API_KEY")
        self.model_name = model_name
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.max_retries = max_retries
        self.is_available = False
        
        # Load template context for enhanced prompts
        self.template_context = self._load_template_context()
        
        # Initialize LangChain components
        try:
            if not self.api_key:
                raise ValueError("GROQ_API_KEY environment variable is required")
                
            from langchain_groq import ChatGroq
            from langchain.prompts import PromptTemplate
            from langchain.schema import HumanMessage
            
            self.llm = ChatGroq(
                groq_api_key=self.api_key,
                model_name=self.model_name,
                temperature=self.temperature,
                max_tokens=self.max_tokens
            )
            
            self.prompt_template = self._create_enhanced_prompt_template()
            self.is_available = True
            logger.info(f"Pure LLM handler initialized with model: {self.model_name}, retries: {self.max_retries}")
            
        except (ImportError, ValueError) as e:
            logger.warning(f"Pure LLM handler not available: {e}")
            self.is_available = False
    
    def _load_template_context(self) -> Dict[str, Any]:
        """Load template context from template.json for enhanced prompts."""
        template_path = Path("template.json")
        
        try:
            with open(template_path, 'r', encoding='utf-8') as f:
                template_data = json.load(f)
            
            # Extract template mappings (exclude CDF_META)
            context = {}
            for erp_name, erp_data in template_data.items():
                if erp_name == "CDF_META":
                    continue
                context[erp_name] = erp_data
            
            logger.info(f"Loaded template context for {len(context)} ERP systems")
            return context
            
        except Exception as e:
            logger.warning(f"Failed to load template context: {e}")
            return {}
    
    def _create_enhanced_prompt_template(self):
        """Create enhanced prompt template with rich template context."""
        from langchain.prompts import PromptTemplate
        
        template = """You are an expert ERP data integration specialist with deep knowledge of enterprise systems. Your task is to map column names from unknown ERP data to standardized CDF (Common Data Frame) format using your expertise and the provided template examples.

# Pure LLM-Based ERP to CDF Column Mapping

**Target Entity Type**: {entity}

**Your Data Columns (Unknown ERP)**:
{source_columns}

**Target CDF Schema for {entity}**:
{target_columns}

**Template Examples from Known ERP Systems**:
{template_examples}

**Entity-Specific Mapping Guidance**:
{entity_guidance}

**Your Expert Instructions**:
1. Analyze the source column names and understand their business meaning
2. Use the template examples to understand common ERP naming patterns
3. Map each source column to the most semantically appropriate CDF column
4. Consider variations in naming conventions (abbreviations, prefixes, suffixes)
5. Only map columns where you have high confidence in the semantic match
6. If no good match exists for a source column, omit it from the mapping
7. Each CDF column should be mapped to at most one source column

**Critical Requirements**:
- Return ONLY a valid JSON object with the mappings
- Use exact column names from the provided lists
- Ensure semantic accuracy over quantity of mappings
- Consider business context and ERP domain knowledge

**Required Response Format**:
```json
{{
  "source_column_1": "target_cdf_column_1",
  "source_column_2": "target_cdf_column_2"
}}
```

Generate the expert mapping now:"""

        return PromptTemplate(
            template=template,
            input_variables=[
                "entity", 
                "source_columns", 
                "target_columns", 
                "template_examples",
                "entity_guidance"
            ]
        )
    
    def infer_mapping_pure(self, source_columns: List[str], cdf_columns: List[str], 
                          entity: str) -> Dict[str, str]:
        """Infer column mapping using pure LLM approach with enhanced template context.
        
        Args:
            source_columns: Source column names from unknown ERP
            cdf_columns: Target column names for CDF
            entity: Entity type
            
        Returns:
            Dictionary mapping source columns to CDF columns
        """
        if not self.is_available:
            logger.error("Pure LLM handler not available")
            return {}
        
        for attempt in range(self.max_retries):
            try:
                logger.info(f"Pure LLM mapping inference attempt {attempt + 1}/{self.max_retries}")
                
                # Build enhanced template examples
                template_examples = self._build_template_examples(entity)
                
                # Get entity-specific guidance
                entity_guidance = self._get_entity_guidance(entity)
                
                # Format the enhanced prompt
                formatted_prompt = self.prompt_template.format(
                    entity=entity,
                    source_columns=json.dumps(source_columns, indent=2),
                    target_columns=json.dumps(cdf_columns, indent=2),
                    template_examples=template_examples,
                    entity_guidance=entity_guidance
                )
                
                # Get response from LLM
                from langchain.schema import HumanMessage
                response = self.llm.invoke([HumanMessage(content=formatted_prompt)])
                
                # Parse response
                content = response.content.strip()
                
                # Extract and clean JSON
                mapping = self._extract_and_parse_json(content)
                
                # Validate mapping
                if self._validate_mapping(mapping, source_columns, cdf_columns):
                    logger.info(f"Pure LLM mapping successful: {len(mapping)} field mappings")
                    return mapping
                else:
                    logger.warning(f"Invalid mapping generated on attempt {attempt + 1}")
                    
            except Exception as e:
                logger.error(f"Pure LLM API call failed (attempt {attempt + 1}): {e}")
        
        # All attempts failed
        logger.error(f"All {self.max_retries} Pure LLM mapping attempts failed")
        return {}
    
    def _build_template_examples(self, entity: str) -> str:
        """Build rich template examples for the given entity."""
        if not self.template_context:
            return "No template examples available."
        
        examples = []
        
        # Select diverse ERP systems for examples
        priority_erps = ["NetSuite", "SAP ERP", "Oracle Fusion", "Microsoft Dynamics", "Workday"]
        
        for erp_name in priority_erps:
            if erp_name in self.template_context and entity in self.template_context[erp_name]:
                mapping = self.template_context[erp_name][entity]
                examples.append(f"""
**{erp_name} {entity} mapping**:
{json.dumps(mapping, indent=2)}""")
        
        # Add additional ERPs if we have less than 3 examples
        if len(examples) < 3:
            for erp_name, erp_data in self.template_context.items():
                if erp_name not in priority_erps and entity in erp_data:
                    mapping = erp_data[entity]
                    examples.append(f"""
**{erp_name} {entity} mapping**:
{json.dumps(mapping, indent=2)}""")
                    if len(examples) >= 5:  # Limit to 5 examples
                        break
        
        if not examples:
            return f"No template examples available for entity: {entity}"
        
        return "\n".join(examples)
    
    def _extract_and_parse_json(self, content: str) -> Dict[str, str]:
        """Extract and parse JSON from LLM response with multiple fallback methods."""
        
        # Method 1: Extract from code blocks
        if "```json" in content:
            json_start = content.find("```json") + 7
            json_end = content.find("```", json_start)
            if json_end != -1:
                content = content[json_start:json_end].strip()
        elif "```" in content:
            json_start = content.find("```") + 3
            json_end = content.find("```", json_start)
            if json_end != -1:
                content = content[json_start:json_end].strip()
        
        # Method 2: Find JSON object boundaries
        json_start = content.find("{")
        json_end = content.rfind("}") + 1
        if json_start != -1 and json_end > json_start:
            content = content[json_start:json_end]
        
        # Method 3: Clean up common issues
        content = content.replace("'", '"')  # Single to double quotes
        content = content.replace('\n', ' ')  # Remove newlines
        
        try:
            return json.loads(content)
        except json.JSONDecodeError as e:
            logger.error(f"JSON parsing failed: {e}")
            logger.error(f"Content: {repr(content)}")
            
            # Method 4: Regex extraction as fallback
            try:
                import re
                pattern = r'"([^"]+)"\s*:\s*"([^"]+)"'
                matches = re.findall(pattern, content)
                if matches:
                    mapping = {}
                    used_targets = set()
                    for source, target in matches:
                        if target not in used_targets:
                            mapping[source] = target
                            used_targets.add(target)
                    return mapping
            except Exception as regex_error:
                logger.error(f"Regex fallback failed: {regex_error}")
            
            return {}
    
    def _get_entity_guidance(self, entity: str) -> str:
        """Get comprehensive entity-specific mapping guidance."""
        guidance_map = {
            "sales_orders": """
**Sales Orders Mapping Patterns**:
- **Order IDs**: Look for order numbers, transaction IDs, document numbers
  Common patterns: order_id, order_num, tranId, OrderNum, VBELN, so_nbr, OrderNo
- **Dates**: Order dates, transaction dates, creation dates
  Common patterns: order_date, trandate, OrderDate, ERDAT, so_ord_date, odat
- **Customer References**: Customer IDs, account numbers, entity references
  Common patterns: customer_id, entity, CustNum, KUNNR, so_cust, otbp
- **Amounts**: Total amounts, order values, net amounts
  Common patterns: total_amount, total, OrderAmt, NETWR, so_total_amt, oamt
- **Status**: Order status, document status, processing status
  Common patterns: status, OrderHeld, AUART, so_stat, stat
- **Currency**: Currency codes, currency references
  Common patterns: currency, CurrencyCode, WAERK, so_curr, curr
- **Line Items**: Item IDs, descriptions, quantities, prices
  Common patterns: item_id, description, quantity, unit_price, line_total
            """.strip(),
            
            "customers": """
**Customer Mapping Patterns**:
- **Customer IDs**: Customer numbers, account IDs, entity IDs
  Common patterns: customer_id, CustNum, KUNNR, cm_addr, CustomerId
- **Names**: Customer names, company names, party names
  Common patterns: customer_name, Name, NAME1, cm_name, CustomerName
- **Contact Info**: Email addresses, phone numbers, contact details
  Common patterns: contact_email, phone_number, Email, TELF1, cm_phone
- **Company Flags**: Organization type, party type, customer type
  Common patterns: is_company, PartyType, KTOKD, cm_type, CustomerType
- **Status**: Customer status, blocked status, active status
  Common patterns: status, Blocked, SPERR, cm_sort, CustomerStatus
- **Addresses**: Address lines, city, state, postal codes, country
  Common patterns: address_line1, city, state, postal_code, country
- **Dates**: Creation dates, modification dates, established dates
  Common patterns: created_date, last_modified, ERDAT, AEDAT
            """.strip(),
            
            "invoices": """
**Invoice Mapping Patterns**:
- **Invoice IDs**: Invoice numbers, document numbers, transaction IDs
  Common patterns: invoice_id, InvoiceNum, VBELN, ih_inv_nbr, InvoiceNo
- **Dates**: Invoice dates, transaction dates, due dates
  Common patterns: invoice_date, due_date, InvoiceDate, FKDAT, ih_inv_date
- **Customer References**: Customer IDs, bill-to customers, account numbers
  Common patterns: customer_id, CustNum, KUNAG, ih_cust, CustomerId
- **Amounts**: Invoice amounts, total amounts, balance amounts
  Common patterns: total_amount, InvoiceAmt, NETWR, ih_amt, GrossAmount
- **Status**: Invoice status, payment status, document status
  Common patterns: status, OpenInvoice, FKSTO, ih_stat, InvoiceStatus
- **Line Items**: Item details, descriptions, quantities, prices
  Common patterns: item_id, description, quantity, unit_price, line_total
            """.strip(),
            
            "purchase_orders": """
**Purchase Order Mapping Patterns**:
- **PO IDs**: Purchase order numbers, document numbers
  Common patterns: po_id, PONUM, EBELN, poh_nbr, OrderNo
- **Dates**: Order dates, creation dates, delivery dates
  Common patterns: po_date, OrderDate, BEDAT, poh_ord_date, OrderDate
- **Vendor References**: Vendor IDs, supplier IDs, vendor numbers
  Common patterns: vendor_id, VendorNum, LIFNR, poh_vend, SupplierId
- **Amounts**: Total amounts, order amounts, net amounts
  Common patterns: total_amount, TotalOrder, NETWR, GrossAmount
- **Status**: Order status, document status, approval status
  Common patterns: status, OpenOrder, BSTYP, poh_stat, OrderStatus
- **Expected Dates**: Receipt dates, delivery dates, due dates
  Common patterns: expected_receipt_date, DueDate, EINDT, pod_due_date
            """.strip(),
            
            "inventory_items": """
**Inventory Item Mapping Patterns**:
- **Item IDs**: Item numbers, part numbers, material numbers, SKUs
  Common patterns: item_id, PartNum, MATNR, pt_part, ItemId
- **Names**: Item names, part descriptions, material descriptions
  Common patterns: item_name, PartDescription, MAKTX, pt_desc1, Name
- **Descriptions**: Detailed descriptions, long descriptions
  Common patterns: description, SearchWord, pt_desc2, DetailedDescription
- **Pricing**: Base prices, unit prices, list prices, costs
  Common patterns: base_price, cost_price, UnitPrice, STPRS, pt_price
- **Quantities**: On-hand quantities, available quantities, stock levels
  Common patterns: quantity_on_hand, InventQtyAvail, LABST, QtyOnHand
- **Status**: Active status, inactive flags, obsolete flags
  Common patterns: is_active, InActive, MSTAE, pt_status, Obsolete
- **Vendor Info**: Preferred vendors, supplier references
  Common patterns: preferred_vendor_id, PrimPRec, LIFNR, pt_vend
            """.strip()
        }
        
        return guidance_map.get(entity, f"General mapping guidance for {entity} entity.")
    
    def _validate_mapping(self, mapping: Dict[str, str], 
                         source_columns: List[str], cdf_columns: List[str]) -> bool:
        """Validate the generated mapping with enhanced checks."""
        if not isinstance(mapping, dict):
            logger.warning("Mapping is not a dictionary")
            return False
        
        if not mapping:
            logger.warning("Empty mapping generated")
            return False
        
        # Check source columns
        invalid_sources = [col for col in mapping.keys() if col not in source_columns]
        if invalid_sources:
            logger.warning(f"Invalid source columns in mapping: {invalid_sources}")
            return False
        
        # Check target columns
        invalid_targets = [col for col in mapping.values() if col not in cdf_columns]
        if invalid_targets:
            logger.warning(f"Invalid target columns in mapping: {invalid_targets}")
            return False
        
        # Check for duplicate target mappings
        target_counts = {}
        for target in mapping.values():
            target_counts[target] = target_counts.get(target, 0) + 1
        
        duplicates = [target for target, count in target_counts.items() if count > 1]
        if duplicates:
            logger.warning(f"Duplicate target mappings found: {duplicates}")
            return False
        
        logger.info(f"Mapping validation successful: {len(mapping)} valid mappings")
        return True
    
    def detect_entity_type(self, columns: List[str], available_entities: List[str]) -> Optional[str]:
        """Detect the most likely entity type based on column names using LLM.
        
        Args:
            columns: List of column names from the data
            available_entities: List of available entity types to choose from
            
        Returns:
            Detected entity type or None if detection fails
        """
        if not self.is_available:
            logger.error("Pure LLM handler not available for entity detection")
            return None
        
        for attempt in range(self.max_retries):
            try:
                logger.info(f"Entity detection attempt {attempt + 1}/{self.max_retries}")
                
                # Create entity detection prompt
                prompt = self._create_entity_detection_prompt(columns, available_entities)
                
                # Get response from LLM
                from langchain.schema import HumanMessage
                response = self.llm.invoke([HumanMessage(content=prompt)])
                
                # Parse response
                content = response.content.strip()
                
                # Extract entity type from response
                detected_entity = self._extract_entity_from_response(content, available_entities)
                
                if detected_entity and detected_entity in available_entities:
                    logger.info(f"Entity detection successful: {detected_entity}")
                    return detected_entity
                else:
                    logger.warning(f"Invalid entity detected on attempt {attempt + 1}: {detected_entity}")
                    
            except Exception as e:
                logger.error(f"Entity detection API call failed (attempt {attempt + 1}): {e}")
        
        # All attempts failed
        logger.error(f"All {self.max_retries} entity detection attempts failed")
        return None
    
    def _create_entity_detection_prompt(self, columns: List[str], available_entities: List[str]) -> str:
        """Create prompt for entity type detection."""
        return f"""You are an expert ERP data analyst. Analyze the following column names and determine the most likely business entity type they represent.

**Column Names to Analyze**:
{json.dumps(columns, indent=2)}

**Available Entity Types**:
{json.dumps(available_entities, indent=2)}

**Entity Type Characteristics**:

**sales_orders**: Order management data
- Typical columns: order_id, order_date, customer_id, total_amount, status, currency, item_id, quantity, unit_price, line_total
- Business context: Customer orders, sales transactions, order processing

**customers**: Customer/client master data  
- Typical columns: customer_id, customer_name, contact_email, phone_number, is_company, status, address_line1, city, state, country
- Business context: Customer information, contact details, addresses

**invoices**: Billing and invoice data
- Typical columns: invoice_id, invoice_date, customer_id, total_amount, due_date, status, currency, item_id, quantity, unit_price
- Business context: Billing documents, payment processing, accounts receivable

**purchase_orders**: Procurement and purchasing data
- Typical columns: po_id, po_date, vendor_id, total_amount, status, currency, expected_receipt_date, item_id, quantity
- Business context: Vendor orders, procurement, accounts payable

**inventory_items**: Product/item master data
- Typical columns: item_id, item_name, description, base_price, cost_price, quantity_on_hand, is_active, unit_type
- Business context: Product catalog, inventory management, stock levels

**Analysis Instructions**:
1. Look for key identifying patterns in the column names
2. Consider the business domain and data relationships
3. Match column patterns to the most appropriate entity type
4. Focus on the primary business purpose of the data

**Response Format**:
Return ONLY the entity type name from the available options. No explanation needed.

**Example Responses**:
- sales_orders
- customers  
- invoices
- purchase_orders
- inventory_items

Analyze the columns and return the most likely entity type:"""
    
    def _extract_entity_from_response(self, content: str, available_entities: List[str]) -> Optional[str]:
        """Extract entity type from LLM response."""
        content = content.strip().lower()
        
        # Direct match
        for entity in available_entities:
            if entity.lower() == content:
                return entity
        
        # Partial match
        for entity in available_entities:
            if entity.lower() in content:
                return entity
        
        # Try to find any of the available entities in the response
        for entity in available_entities:
            if entity.replace('_', ' ').lower() in content or entity.replace('_', '').lower() in content:
                return entity
        
        logger.warning(f"Could not extract valid entity from response: {content}")
        return None


def create_pure_llm_handler(**kwargs) -> PureLLMHandler:
    """Factory function to create Pure LLM handler.
    
    Args:
        **kwargs: Additional arguments for handler initialization
        
    Returns:
        Pure LLM handler instance
    """
    return PureLLMHandler(**kwargs)